Abdul Jabbar Abdul Jabbar - 2 years ago 130
Javascript Question

drawImage in JavaScript (Canvas)

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)

Answer Source

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:

if(A.name == 'image' && A.pageNum == pNum)
{
    displayImage(A.path, A.x, A.y, A.w, A.h);

}
function displayImage(path, x, y, w, h)
{
    var img = new Image();
    img.src = path;

    img.onload = function() {
        context.drawImage(img, x, y, w, h);
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download