views:

502

answers:

3

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?

A: 

First, I'd see if there's a bug report in on this for either browser.

Meanwhile, you could use setInterval, or maybe just a loop, to just check whether .getContext (without brackets) is true, and only proceed after it is (with some sensible limit so you don't stall the browser with an infinite loop if something goes wrong or a user doesn't have that feature in their browser.)

Kev
(This is admittedly ugly and not all that efficient, but there may not be something better to use. :( )
Kev
A: 

You could attach a function to the DOMReady event of the canvas.

RC
Ooh, that sounds cool. I hope it works.
Kev
How would I go about that with jQuery? Using $(canvaselement).ready(function() { }); indeed triggers, but the getContext is still not available.
Alex Morse
+2  A: 

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.

Mauricio
d'Oh, obvious mistake! That was it. I had an earlier version where I hadn't wrapped the document.createElement in jQuery, and forgot to compensate when I did.
Alex Morse