I have an array of image objects which hold all the necessary info like path,x, y, w, h. Now i want to draw all those images on canvas in a loop.. but when i do so, it only draws the first image. Here is the code:
for(var i=0; i<shapes.length; i++)
{
var A = shapes.pop();
if(A.name == 'image' && A.pageNum == pNum)
{
var img = new Image();
img.src = A.path;
img.onload = function() {
context.drawImage(img, A.x, A.y, A.w, A.h);
}
}
}
i checked all the info in the shapes array... inside the if condition, before calling drawImage function, all the info of each image is correct but for some strange reason it doesn't display images except the 'last' in the array (the one which pops out last)
It was the problem of some sort of closure... like, the loop finishing before images getting loaded or something. The solution that worked for me was putting all the image loading code in a separate function and calling that function from the loop: