views:

43

answers:

1

I am running into problems when trying to draw a large 2D array of images onto a canvas. Using a separate program, I'm taking one big image file and breaking it up smaller, uniform pieces. I'm using the 2D array to represent this "grid" of images, and ideally when I assign the src of each element in the grid, that image would be drawn to its proper point on the canvas once its ready. However, my code isn't working.

var grid = new Array()  
/*grid is set to be a 2D array of 'totalRows' rows and 'totalCols' columns*/  

/*In the following code, pieceWidth and pieceHeight are the respective height/widths  
of each of the smaller 'pieces' of the main image. X and Y are the coordinates on  
the canvas that each image will be drawn at. All of the images are located in the  
same directory (The src's are set to http://localhost/etc), and each individual  
filename is in the form of name(row*totalRows + col).png, ex, traversing the 2D  
array left to right top to bottom would give image1.png, image2.png, etc*/  

for (var row = 0; row < totalRows; row++)  
    {  
        for (var col = 0; col < totalCols; col++)  
        {  
            grid[row][col] = new Image();  
            var x = col * pieceWidth;  
            var y = row * pieceHeight;  
            grid[row][col].onload = function () {ctx.drawImage(grid[row][col], x, y);};  
            grid[row][col].src = "oldimagename" +  ((row * totalRows) + col) + ".png";  
        }  
    }  

I have tried running this code in Opera, Firefox, Chrome, and Safari. The onload events don't fire at all in Opera, Chrome, and Safari (I placed an alert inside the onload function, it never came up). In Firefox, only the FIRST image (grid[0][0])'s onload event fired. However, I noticed that if I placed an alert right AFTER I set the src of the current element, every onload event in Firefox gets triggered, and the entire image is drawn. Ideally I would like this to work in all 4 browsers (I assume IE wont work because it doesn't support Canvases), but I just don't know what is going on. Any help/input is appreciated, thanks!

A: 

I think the problem is that you're not getting your variables into a closure. Change this line:

grid[row][col].onload = function () {ctx.drawImage(grid[row][col], x, y);};

To

grid[row][col].onload = function () {window.alert('row:' + row + ' col:' + col);};

And what you'll see is that your alerts are returning the same value for row and col on each call. You need to get these variables wrapped in a closure so that your function deals with the values and not the references:

var drawCanvasImage = function(ctx,grid,row,col,x,y) {
    return function() {
        ctx.drawImage(grid[row][col], x, y);
    }
}

Then do:

grid[row][col].onload = drawCanvasImage(ctx,grid,row,col,x,y);

This example page works for me in Firefox and Chrome.

robertc
Thank you so much! That was the issue right there.
Kaz