I wanted to make a short cut for writing all the onload functions for my images by looping through an object's variables called GameImages
. I'm not sure why the images aren't being loaded when I look in the developer console in chrome. Is the for loop interrupting the loading of the images? How can I load the images in a loop instead of writing each onload function?
var i = 1; //set increment variable
var GameImages = { //object to hold each image
game1 : new Image(),
game2 : new Image(),
game3 : new Image(),
game4 : new Image(),
game5 : new Image(),
};
for(gameImage in GameImages) { //loop through each image
gameImage.onload = function () { //set the onload function for the current image
gamePosters.push(gameImage);
console.log(gamePosters.length); //print out the new size of the gamePosters array
};
//give source of image. (my images are named game1.jpg, game2.jpg, etc.)
gameImage.src = "images/assets/posters/games/game" + i + ".jpg";
i += 1; //increment i
}
It is because you're for (gameImage in GameImages)
loop is looping through each of your GameImage object's properties (ie gameImage is first "game1", then "game2", etc.). Change your code to:
for (game in GameImages) {
var gameImage = GameImages[game]; // This will get your actual Image
gameImage.onload = function () {
gamePosters.push(gameImage);
console.log(gamePosters.length);
};
//give source of image. (my images are named game1.jpg, game2.jpg, etc.)
gameImage.src = "images/assets/posters/games/game" + i + ".jpg";
i += 1; //increment i
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.