简体   繁体   中英

In Javascript - How do I change the image a variable points to without reloading it?

I'm making a rudimentary game to learn Javascript, and drawing to the HTML canvas with images. I preload the images so they display when the game starts, but after the first time the images don't display, suggesting they're being reloaded.

This is executed on page load:

function preload() {
for (i = 0; i < preload.arguments.length; i++){
    images[i] = new Image();
    images[i].src = preload.arguments[i];
    }
}
preload("images/background.png", "images/character.png", "images/dragon.png", "images/humanOpponent.png","images/ooze.png","images/tinyCharacter.png");

Part of the function that's called when a battle begins - I know this code is sloppy and things that are handled here should be handled elsewhere, but that's not the focus of the question:

youImage.src = "images/character.png";
background.src = "images/background.png";

if (oppType == "Human")
    {oppHealth = humanOpp.maxHP;
    oppImage.src = humanOpp.image;}
if (oppType == "Ooze")
    {oppHealth = ooze.maxHP;
    oppImage.src = ooze.image;}
if (oppType == "Dragon")
    {oppHealth = dragon.maxHP;
    oppImage.src = dragon.image;
    youImage.src = "images/tinycharacter.png";
    background.src = "images/castleBackground.png";}

I think what's happening is that the images are being reloaded when this function is called But this exact code is called when the game starts up - and the images display there. So I'm baffled.

Does it makes sense to modify it as follows?

var preloadedImages = {};
function preload(images) {
    for (i = 0; i < images.length; i++){
      var img = new Image();
      img.src = images[i][1];
      preloadedImages[images[i][0]] = img;
    }
}
preload([["dragon", "images/dragon.png"], ["human", "images/humanOpponent.png"]]);

Then you can just use:

if (oppType == "Human") {
    oppHealth = humanOpp.maxHP;
    oppImage = preloadedImages['human'];
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM