tes*_*est 3 javascript html5 canvas
我有一个图像文件夹,总共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);
}
}
};
Run Code Online (Sandbox Code Playgroud)
问题是此代码仅加载最后一个tile(在本例中tile[520]).实际上我想加载所有的瓷砖.无论.如何将一组图像放入数组并加载?
小智 6
你修改了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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5200 次 |
| 最近记录: |