JavaScript / HTML5 Canvas - Loading an Image Array

I have a folder with images, total 32x32 tiles. I am trying to load these images using JavaScript on an HTML5 canvas.

Here is what I have:

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

The problem is that this code only loads the last fragment (in this case tile[520]). In fact, I want to download all the tiles. No matter what. How to place a set of images in an array and load it?

+3
source share
2 answers

Change one instance of imageObj; so basically you get an array pointing to the same instance that ends in 520.

to try

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);
} 
+6
source

Not related to your problem, but you may run into it (with current code)

, , , .

+2

All Articles