【发布时间】:2016-06-15 20:06:41
【问题描述】:
我正在创建一个“接住掉落物品”游戏,并已成功将“捕手”图像和“掉落物品”图像绘制到画布上。但我还想在没有捕捉到下落图像并击中我的 html5 画布底部时显示图像(x.png)。 generateX 函数是从 animate 函数中调用的,当一个下落的图像碰到画布的底部时。 sound.play() 正在工作。 generateX 函数中的 console.logs 记录以下内容 - 2,3 | 1,3 | 1,3 - 所以我知道这个函数第一次运行时图像没有完全加载。除了实际的图像显示外,一切似乎都在工作。我试图以其他线程建议的方式构造它,但没有任何效果。非常感谢任何帮助!
generateX: function() {
console.log('inside generateX func');
var imgX = new Image();
imgX.src = 'assets/x.png';
function drawX() {
console.log(3);
counter+=20;
context.drawImage(imgX, xIcon.x + counter, xIcon.y, xIcon.width, xIcon.height);
xArr.push(imgX);
console.log('xArr', xArr);
}
if (imgX.complete) {
console.log(1);
drawX();
} else {
console.log(2);
imgX.onload = drawX;
}
helper.checkMisses();
}
animate: function() {
var sound;
if (continueAnimating) {
requestAnimationFrame(helper.animate);
}
for (var i = 0; i < surveys.length; i++) {
var survey = surveys[i];
if (helper.isColliding(survey, dinoSaurus)) {
sound = new Audio("audio/coinSound.mp3");
sound.play();
score += 5;
helper.resetSurvey(survey);
}
survey.y += survey.speed;
// if the survey is below the canvas,
if (survey.y > canvas.height) {
sound = new Audio("audio/buzzerSound.mp3");
sound.play();
helper.generateX();
helper.resetSurvey(survey);
}
}
// redraw everything
helper.drawAll();
}
--
resetSurvey: function(survey) {
// randomly position survey near the top of canvas
survey.x = Math.random() * (canvas.width - surveyWidth);
survey.y = 40 + Math.random() * 30;
survey.speed = (0.55 + Math.random()) * 0.9;
}
【问题讨论】:
-
imgX可能需要一段时间才能加载,resetSurvey可能会在 img 尝试显示时运行。 resetSurvey 是否正在清除画布? -
这是一个很好的建议 - 但 resetSurvey 不会清除画布。我已经在上面的原始帖子中发布了。
-
在启动游戏之前加载所有图片,然后启动游戏。这里是 mixin 问题(加载和绘图)。