【发布时间】:2015-03-15 05:08:48
【问题描述】:
我尝试使用 HTML Canvas 制作游戏,但遇到了问题。
当我用 'window.onload' 调用我的 'init' 函数时,我的程序不会加载任何图像。画布已创建,但图像不存在,当我在 chrome 控制台中提交我的功能时,图像出现......所以我想加载我的图像并在完成后执行该功能。
感谢您的帮助!
var requestAnimId;
// Initialisation
function init() {
var tilemapCtx = new Canvas('tilemap', 800, 600, 1);
var tilemap = new Tilemap("sand", tilemapCtx);
requestAnimId = window.requestAnimationFrame(update);
}
// Boucle de rafraîchissement
function update() {
requestAnimId = window.requestAnimationFrame(update);
}
window.onload = init;
这是瓷砖地图:
var Tilemap = function(map, canvas) {
for (var y = 0; y < 10; y++) {
for (var x = 0; x < 10; x++) {
// Création de la tile
this.image = new Image();
// Définition de l'image
switch(tilemaps[map][y][x]) {
case " ":
this.image.src = "assets/sand.png";
break;
case "#":
this.image.src = "assets/wall.png";
break;
}
// Affichage de l'image
//canvas.drawImage(this.image, tileX, tileY, tilesetWidth, tilesetHeight, x, y, 32, 32);
canvas.drawImage(this.image, 32, 32);
}
}
}
和画布:
var Canvas = function(name, width, height, zIndex) {
this.canvas = window.document.createElement("canvas");
this.canvas.id = name;
this.canvas.style.position = "absolute";
this.canvas.width = width;
this.canvas.height = height;
this.canvas.style.zIndex = zIndex;
document.body.appendChild(this.canvas);
return this.canvas.getContext('2d');
}
【问题讨论】:
标签: javascript html canvas