【发布时间】: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