I try to make a game with HTML Canvas but I've a problem.
When I call my 'init' function with 'window.onload', my program doesn't load any images. The canvas has been created, but images aren't there, and when I submit my function in chrome console, images appears... So I want to load my images and execute the function when it's done.
Thanks for help !
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;
Here is Tilemap :
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);
}
}
}
and Canvas :
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');
}