0

我正在制作一个基本的游戏来学习 Javascript,并用图像绘制到 HTML 画布上。我预加载了图像,以便它们在游戏开始时显示,但在第一次之后图像不显示,表明它们正在重新加载。

这是在页面加载时执行的:

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");

战斗开始时调用的部分函数 - 我知道这段代码很草率,这里处理的事情应该在其他地方处理,但这不是问题的重点:

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";}

我认为发生的事情是在调用此函数时正在重新加载图像但是当游戏启动时会调用这个确切的代码 - 并且图像显示在那里。所以我很困惑。

4

1 回答 1

0

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'];
}
于 2013-10-14T16:10:42.307 回答