6

I am having a problem with a canvas element. It does not show when it is in a hidden div and the div is toggled. better explanation and example here

http://jsfiddle.net/78sJT/10/

This is happening in ff and chrome (not tested others). Could anyone tell me why / how to overcome this issue.

dogmatic69
  • 7,574
  • 4
  • 31
  • 49

2 Answers2

2

I just hit this issue in Chrome 37.0.2062.124 m, matching the problem described in the OP's question. However I'm not using any particular graphing library, just drawing to canvas. And I was already re-drawing the canvas when the enclosing DIV's size changed.

I find that if a canvas's width or height is set to zero, it becomes unreliable. The next time you set the width and height to non-zero values, any drawing you do on it immediately will be ignored, even though its width and height are now non-zero and it can be seen in the element tree (and hover-highlighted in the page) in Chrome's debugger.

So in addition to the advice in benni_mac_b's answer you must either:

  • use setTimeout or similar to delay drawing on the canvas, so you don't do it immediately after setting width/height, or
  • make sure you never set the canvas to zero width/height. Make sure it is at least 1 pixel.

I do the later for simplicity and it solves the problem.

In summary:

A canvas that has just grown from (0, 0) to (1000, 1000) cannot be drawn on immediately - it ignores all drawing instructions. But if it has just grown from (1, 1) to (1000, 1000) you can immediately draw on all of it.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
2

The issue is that dygraphs detects the div's width/height as 0/0 and doesn't learn otherwise until it's redrawn (there is no JS event which fires when an individual DOM element is resized).

The easiest workaround is to just explicitly let the dygraph know it should update its size and redraw itself after the div is toggled using g.resize();

    $(document).ready(function(){
      $('.click').click(function(){
        $('#hidden').toggle();
        g.resize();
      });
    });

I updated your jsfiddle http://jsfiddle.net/78sJT/13/

benni_mac_b
  • 8,803
  • 5
  • 39
  • 59
  • thank you, this has been driving me crazy. I will just have to figure out a way to do that as I am generating the charts dynamically and don't know what "g" actually is. – dogmatic69 Jan 21 '12 at 02:14
  • 1
    Got it working, for anyone else that is looking at doing this dynamically I am using html5 data attributes and ended up with http://codepad.org/CmHHo0iG – dogmatic69 Jan 21 '12 at 13:29