Skip to content Skip to sidebar Skip to footer

Loading Multiple Images Into Multiple Canvases

I got a code for loading an image into a canvas, and it works fine, but when I try to iterate to do it multiple times, it only loads one image (the last one). Anyone knows why? <

Solution 1:

The var img is being overwritten as you loop. The onloads will not be called until the current execution is complete. By that time img will equal the 3rd iteration.

To fix

var pics = [ 'Desert.jpg', 'Hydrangeas.jpg' ];
functionloadImage(i){
    var img = newImage();
    var ctx = $( '#canvas_'+(i+1) )[0].getContext('2d');
    img.onload = function() { 
        ctx.drawImage(img, 0, 0);
    };
    img.src = pics[i];
}

for(var i=0; i < pics.length; i++) {
     loadImage(i);
}

The call to the function loadImage creates a new reference to all the variable each time it is called. It differs from onload because it is called immediately, while onload is a callback and must wait until the currently executing context has completely exited (in other words returned until there are no more returns), then and only then can the onload happen.

Post a Comment for "Loading Multiple Images Into Multiple Canvases"