[英]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. 我正在做一个基本的游戏来学习Javascript,并用图像绘制到HTML画布上。 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'];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.