![](/img/trans.png)
[英]Using a JavaScript while loop to draw an array of images to HTML5 canvas
[英]JavaScript/HTML5 Canvas - Load array of images
我有一个图像文件夹,总共32x32瓷砖。 我正在尝试使用JavaScript将这些图像加载到HTML5画布上。
这就是我所拥有的:
window.onload = function(){
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var imageObj = new Image();
var tiles = [];
canvas.width = 512;
canvas.height = 352;
for (x = 0; x <= 520; x++) {
imageObj.src = "line_tile/t"+x+".png";
tiles.push(imageObj);
}
var theX;
var theY;
for (x = 0; x <= 10; x++) {
for (y = 0; y <= 15; y++) {
theX = x*32;
theY = y*32;
context.drawImage(tiles[2], theY, theX,32,32);
console.log("Tile X: "+x+" | Tile Y: "+y+" - X Pos: "+theX+" | Y Pos: "+theY);
}
}
};
问题是此代码仅加载最后一个tile(在本例中为tile[520]
)。 实际上我想加载所有的瓷砖。 无论。 如何将一组图像放入数组并加载?
你修改了imageObj的单个实例; 所以基本上你最终得到的数组都指向同一个实例,以520结尾。
尝试
for (x = 0; x <= 520; x++) {
var imageObj = new Image(); // new instance for each image
imageObj.src = "line_tile/t"+x+".png";
tiles.push(imageObj);
}
与您的问题没有严格关联,但您可能会遇到它(使用当前代码)
在将它添加到tiles数组之前,我不确定您是否首先需要查看Image是否实际已加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.