5

I'm trying to draw in a canvas while its parent is display:none. Is there a way to do that?

Here is a jsFiddle to demonstrate my problem: http://jsfiddle.net/kannix/jSj83/

If you just click draw, everything works as expected. If you click Show/Hide and while hidden, click the Draw Button, a click on Show/Hide will reveal the canvas but its still empty.

kannix
  • 5,107
  • 6
  • 28
  • 47

3 Answers3

8

You can use the css visibility attribute to hide the div rather than using display

example:

$('#hideBtn').click(function () {
    var hider = $('#hider');
    if(hider.css('visibility') == 'visible') {
        hider.css('visibility', 'hidden');
    }
    else {
        hider.css('visibility', 'visible');
    }
});

Also this line:

ctx.clearRect(0, 0, 100, 100);

Seems to be clearing the drawing.

Todd
  • 317
  • 1
  • 11
4

You cannot do that.

The canvas, while technically there, cannot be interacted with in that way. You could, however, instruct the canvas to draw a specific image while it's hidden. Just make sure you don't clear it when showing.

The user cannot draw while it is hidden though.

If you just want what is drawn to stay visible after clicking show/hide, remove ctx.clearRect(0, 0, 100, 100); from your jQuery.

Irgendw Pointer
  • 1,770
  • 3
  • 30
  • 67
Jacques ジャック
  • 3,682
  • 2
  • 20
  • 43
  • damn i've overseen that clear and thought i can't draw in an invisible canvas.. so it seems like my real code has an other problem – kannix Nov 25 '13 at 18:54
3

A few issues, then it works for you:

  • Don’t clear the canvas in #hideBtn.click
  • Use ctx.beginPath() to initialize a path before ctx.arc
  • Use jQuery <2.0 when fiddling.

Here is code and a Fiddle: http://jsfiddle.net/m1erickson/X7pcm/

var ctx = $('#cnv')[0].getContext('2d');

$('#hideBtn').click(function () {
    $('#hider').toggle();        

});

$('#drawBtn').click(function () {
    ctx.beginPath();
    ctx.arc(50, 50, 15, 0, 2*Math.PI);
    ctx.fillStyle = '#000000';
    ctx.fill();
});
markE
  • 102,905
  • 11
  • 164
  • 176