I am using the following code to wait for all images to load before drawing them onto the canvas. This works great in Firefox and works great when I enter the url of the page directly into the address bar of Chrome. However, when I attempt to use the refresh button in Chrome the images fail to load.

    var need_to_load = 2;
    var items = 0;

    function item_loaded() {
            items +=1;
            if (items >= need_to_load) {
                    context.drawImage(router_pic,router_x,router_y,80,80);
                    context.drawImage(switch_pic,router_x,switch_y,60,60);
            }
    } // end item_loaded

    var router_pic = new Image();
    router_pic.src = "images/router.png";
    router_pic.onload = item_loaded();
    var switch_pic = new Image();
    switch_pic.src = "images/switch.png";
    switch_pic.onload = item_loaded();

Can someone point me in the right direction as to why and how to make this work with Chrome?

I realize in this case I can get rid of the item_loaded() function, but I have another more complicated canvas drawing where it makes the most sense to wait for all images to load before drawing them to the canvas.

Chrome version is 33.0.1750.152 if that makes any difference.

有帮助吗?

解决方案

You're currently using the onload handler wrong. It need to have only a reference to the handlers - here the result of those functions are returned to it instead.

Simply change these lines:

router_pic.onload = item_loaded;  //no parenthesis
switch_pic.onload = item_loaded;

I would also recommend switching the onload line with src line so src comes last.

Hope this helps!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top