Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas in a div with display none does not work

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.

like image 665
dogmatic69 Avatar asked Oct 09 '22 23:10

dogmatic69


2 Answers

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/

like image 180
benni_mac_b Avatar answered Oct 13 '22 11:10

benni_mac_b


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.

like image 21
Daniel Earwicker Avatar answered Oct 13 '22 11:10

Daniel Earwicker