I have the following simple JavaScript that loads a bunch of images and places them on HTML canvas (canvasCTX is the 2D canvas context):
for (var i=0 ;i<10; i++) {
var placementX = i*25;
var imageObj = new Image();
imageObj.src = 'assets/png/' + i + '.png';
imageObj.onload = function() {
canvasCtx.drawImage(imageObj,placementX,0);
};
}
Now the problem I find is that all the images are placed at the same place - the last variable created by the loop. I think that's because the for loop continues to run whilst images are being loaded, as the onload is an asynchronous event.
How do I make sure each image gets the correct placementX
from it's turn in the for loop
?