Drawing multiple images to a canvas using image.onload

前端 未结 1 1392
孤城傲影
孤城傲影 2021-02-09 20:32

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, uni

1条回答
  •  一整个雨季
    2021-02-09 21:07

    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.

    0 讨论(0)
提交回复
热议问题