Drawing multiple images to a canvas using image.onload

牧云@^-^@ 提交于 2019-12-03 07:47:57

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!