Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing multiple HTML canvases only draws the last one?

In an application I'm writing there is a page where I load multiple base64-encoded images from my database and place them inside a JavaScript array. This is happening on the server via EJS templating, so when the user receives the HTML page the base64-encoded images are present (I checked this).

Next step is using JavaScript on the client-side to loop over the canvases and then fill each canvas with its corresponding image data. However, I'm getting some strange behaviour. Only the last canvas is filled each time.

for (var i = 1; i < 13; i++) {
    var ctx = document.getElementById('canvas-' + i).getContext('2d'),
        image = new Image();

    image.onload = function() {
        ctx.drawImage(image, 0, 0);
    }
    image.src = images[(i - 1)];
}

The images array is defined right above this code (in the same scope). If I execute the code like this only the last canvas (with the id 'canvas-12') will be filled. If I lower the for loop end condition to for example i < 11, only canvas with id 'canvas-10' will be filled.

Is there something I'm missing?

like image 656
lunanoko Avatar asked Dec 15 '22 16:12

lunanoko


1 Answers

Seems like a closure issue; each time you go through to loop, you are changing the object ctx included in the onload function. You need to make sure that you aren't updating the objects during the loop by using a closure:

for (var i = 1; i < 13; i++) {
    var ctx = document.getElementById('canvas-' + i).getContext('2d'),
        image = new Image();
    (function(ctx, image) {
        image.onload = function() {
            ctx.drawImage(image, 0, 0);
        }
        image.src = images[(i - 1)];
    })(ctx, image);
}

NOTE: I have not tested this.

like image 85
Mathletics Avatar answered Dec 18 '22 04:12

Mathletics