【发布时间】:2015-09-07 13:38:57
【问题描述】:
我一直在想这件事。我花了 3 个小时尝试不同的方法并在网上找到解决方案,但我仍然没有修复它。 我有两个单独的图像(不是精灵表),它们需要一个接一个地显示,作为动画,无限。这是我最新的代码:
var canvas, context, imageOne, imageTwo, animation;
function init(){
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
imageOne = new Image();
imageTwo = new Image();
imageOne.src = "catone.png";
imageTwo.src = "cattwo.png";
// Just to make sure both images are loaded
setTimeout(function() { requestAnimationFrame(main);}, 3000);
}
function main(){
animation = {
clearCanvas: function(){
context.clearRect(0, 0, canvas.width, canvas.height);
},
renderImageOne: function(){
context.drawImage(imageOne, 100, 100);
},
renderImageTwo: function(){
context.drawImage(imageTwo, 100, 100);
}
};
animation.renderImageOne();
// I also tried calling animation.clearCanvas();
context.clearRect(0, 0, canvas.width, canvas.height);
animation.renderImageTwo();
// I put this here to confirm that the browser has entered the function, and that it hasn't stopped after animation.renderImageTwo();
console.log("cats");
requestAnimationFrame(main);
}
init();
但问题是只显示了一张图像,而且它没有移动。我在控制台中看不到任何错误或警告。我还确定 HTML 和 JavaScript 已正确连接,并且图像位于正确的路径中。所以无论如何,只显示第一个函数中的图像。示例:animation.renderImageOne();显示 catone,但如果我将其替换为 animation.renderImageTwo();它显示 cattwo。
【问题讨论】:
标签: javascript html canvas