Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when a canvas is ready for manipulation?

Tags:

I am dynamically adding X canvas elements to a page via jQuery like so:

$(document).ready(function() { 
    for(i=0;i<4;i++) {
        var can = $(document.createElement("canvas"))
                   .attr("id","table"+i)
                   .addClass("table")
                   .attr("width",640)
                   .attr("height",480)
                   .appendTo('#container');   
    }

    //...
});

Neither .append() nor .appendTo() have a callback, because they're supposed to happen immediately. Unfortunately, something about the canvas element doesn't happen immediately.

When I go to .getContext('2d') on one of the canvas elements it will fail with "getContext is not a function." This happens on FF 3.5 as well as Chrome.

If I assign and arbitrary event handler to the canvas elements like .click(), and use .getContext() in that event, it works perfectly.

How can I efficiently determine that a canvas is ready for manipulation?

like image 410
Alex Morse Avatar asked Oct 23 '09 21:10

Alex Morse


1 Answers

I don't think you can use getContext() on the can variable.

If you're doing that, try can[0].getContext(). This will actually get the element object, not jQuery's.

like image 105
Mauricio Avatar answered Oct 04 '22 16:10

Mauricio