Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas HTML loading time

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');

}

like image 508
Karz Avatar asked Sep 16 '26 15:09

Karz


1 Answers

Notice that for your tile you only use two images. You use a double loop that will load 100 images.

One problem is you are creating 100 images when in the end you only need two.

Now the reason why your images don't get drawn is because they haven't been loaded. You need to give time for your images to load before you try drawing them.

You need to create an array list of images and make sure they are loaded before you call your init()

This will ensure all your images have been loaded before init() is called.

var len = pics.length;
var loadCounter = 0;
for(var i = 0; i < len; i++) {
    $(document.createElement(img)).attr('src', pics[i]).load(function() {
        alert(pics[i] + 'is loaded');
        loadCounter++;
        if(loadCounter === len) {
            alert("all are loaded");   
        }
    });
}
like image 98
kemicofa ghost Avatar answered Sep 19 '26 05:09

kemicofa ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!