【问题标题】:Drawing multiple images to a canvas using image.onload使用 image.onload 将多个图像绘制到画布上
【发布时间】:2011-03-16 14:15:51
【问题描述】:

尝试在画布上绘制大型二维图像数组时遇到问题。使用一个单独的程序,我将一个大的图像文件分解成更小的、统一的部分。我使用二维数组来表示这个图像“网格”,理想情况下,当我分配网格中每个元素的 src 时,一旦准备好,该图像将被绘制到画布上的适当点。但是,我的代码不起作用。

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";  
        }  
    }  

我尝试在 Opera、Firefox、Chrome 和 Safari 中运行此代码。 onload 事件在 Opera、Chrome 和 Safari 中根本不会触发(我在 onload 函数中放置了一个警报,它从未出现过)。在 Firefox 中,只有第一个图像 (grid[0][0]) 的 onload 事件被触发。但是,我注意到,如果我在设置当前元素的 src 之后立即发出警报,Firefox 中的每个 onload 事件都会被触发,并绘制整个图像。理想情况下,我希望它可以在所有 4 个浏览器中工作(我认为 IE 不会工作,因为它不支持 Canvases),但我只是不知道发生了什么。任何帮助/意见表示赞赏。

【问题讨论】:

    标签: javascript html canvas dom-events onload


    【解决方案1】:

    我认为问题在于您没有将变量放入闭包中。更改此行:

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

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

    what you'll see 是您的警报在每次调用时都为 row 和 col 返回相同的值。您需要获取这些variables wrapped in a closure,以便您的函数处理值而不是引用:

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

    然后做:

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

    This example page 在 Firefox 和 Chrome 中为我工作。

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2014-09-03
      • 2023-03-11
      • 1970-01-01
      • 2012-01-14
      • 2013-11-01
      • 2019-10-19
      • 1970-01-01
      • 2012-11-09
      相关资源
      最近更新 更多