3

I have a folder of images, altogether 32x32 tiles. I am trying to load these images using JavaScript, onto an HTML5 canvas.

Here's 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 up the last tile (in this case tile[520]). In reality I want to load all the tiles. No matter what. How do I properely put a set of images into an array and load it?

2 Answers 2

6

Your modifying a single instance of imageObj; so basically you end up with an array all pointing to the same instance, which ends with 520.

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);
} 
Sign up to request clarification or add additional context in comments.

Comments

2

Not strictly related to your problem but you might encounter it (with current code)

I'm not sure if you do not need first to see if the Image was actually loaded before adding it to the tiles array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.