Christian Dechery
Christian Dechery

Reputation: 876

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?

<pre id="output_1"></pre>
<canvas id="canvas_1"></canvas>
<pre id="output_2"></pre>
<canvas id="canvas_2"></canvas>
<script type="text/javascript">
    var pics = [ 'Desert.jpg', 'Hydrangeas.jpg' ];
    for(var i=0; i < pics.length; i++) {
        var img = new Image();
        var ctx = $( '#canvas_'+(i+1) )[0].getContext('2d');
        img.onload = function() { 
            ctx.drawImage(img, 0, 0);
        };
        img.src = pics[i];
    }
</script>

Upvotes: 1

Views: 479

Answers (1)

Blindman67
Blindman67

Reputation: 54026

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' ];
function loadImage(i){
    var img = new Image();
    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.

Upvotes: 4

Related Questions