最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to detect when a canvas is ready for manipulation? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Aug 15, 2011 at 14:48 Nick Larsen 18.9k6 gold badges69 silver badges97 bronze badges asked Oct 23, 2009 at 21:44 Alex MorseAlex Morse 531 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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.

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.)

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

发布评论

评论列表(0)

  1. 暂无评论