dontHaveName
dontHaveName

Reputation: 1937

js loading images

I have this code

    var a = new Image();
    a.src = objects.a.image;

    var b = new Image();
    b.src = objects.b.image;

    var x = new Image();
    x.src = objects.x.image;

I have about 10 images like this, is there any better way to load it into variables?

Upvotes: 0

Views: 82

Answers (4)

Peter Rasmussen
Peter Rasmussen

Reputation: 16922

You can iterate through the properties of your objects object. Creating a new image per iteration, giving it the source of the property on your objects. Then adding it to the array:

Demo

var arrayOfImg = [];

for(var propt in objects){
    var image = new Image();
    image.src = objects[propt].image;
    arrayOfImg.push(image)
}

console.log(arrayOfImg);

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382102

You normally would use an array to store your images.

For example :

var arr = [];
for (var c='a'.charCodeAt(0); c<='x'.charCodeAt(0); c++) {
     var img = new Image();
     img.src = objects[String.fromCharCode(c)].image;
     arr.push(img);
}

If you really need to add them as variables to the global context, you might do this :

for (var c='a'.charCodeAt(0); c<='x'.charCodeAt(0); c++) {
     var img = new Image();
     var name = String.fromCharCode(c);
     img.src = objects[name].image;
     window[name] = img; // better use somthing's else than window...
}

Note that depending on what really is objects, there might be a more straightforward solution.

Upvotes: 0

Parthik Gosar
Parthik Gosar

Reputation: 11646

This should work

for(var i in objects)
{
    if(objects[i].image)
    {
        var oImage = new Image();
        oImage.src = objects[i].image;
        // if you need the Image object you can store it somewhere
        objects[i].oImgObject = oImage;
     }
}

Upvotes: 1

ulentini
ulentini

Reputation: 2412

Assuming objects contains just images, try this:

var imageList = [];
for (var i in objects) {
    var obj = objects[i];
    var img = new Image();
    img.src = obj.image;
    imageList.push(img);
}

Upvotes: 0

Related Questions