admin管理员组

文章数量:1313162

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?

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?

Share Improve this question edited Apr 21, 2012 at 0:49 Perception 80.6k19 gold badges188 silver badges196 bronze badges asked Apr 21, 2012 at 0:10 testtest 18.2k67 gold badges173 silver badges245 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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);
} 

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.

本文标签: htmlJavaScriptHTML5 CanvasLoad array of imagesStack Overflow