Drawing Multiple Images To A Canvas Using Image.onload
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
Solution 1:
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) {
returnfunction() {
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.
Post a Comment for "Drawing Multiple Images To A Canvas Using Image.onload"