gpt4 book ai didi

javascript - HTML5 逐帧动画(多个图像)

转载 作者:行者123 更新时间:2023-12-02 15:43:06 25 4
gpt4 key购买 nike

我一直在为这件事失去理智。我花了3个小时尝试了不同的方法并在网上找到了解决方案,但我仍然没有解决它。我有两个单独的图像(不是 Sprite 表),它们需要一个接一个地显示,作为动画,无限地显示。这是我的最新代码:

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。

最佳答案

问题出在这里:

  animation.renderImageOne();

// I also tried calling animation.clearCanvas();
context.clearRect(0, 0, canvas.width, canvas.height);

animation.renderImageTwo();

它是否正在绘制第一张图像,清除 Canvas ,然后绘制第二张图像,最后绘制到屏幕上。让您只能看到第二张图像。您将需要一个替代值的变量,并使用它来确定应该绘制哪张图片:

var canvas, context, imageOne, imageTwo, animation;   
var imageToDraw = "one";

然后:

function main() {

...

if(imageToDraw == "one") {
animation.renderImageOne();
imageToDraw = "two";
}
else if(imageToDraw == "two") {
animation.renderImageTwo();
imageToDraw = "one";
}

...
}

注意:您不需要在 main() 内定义 animation,您可以将其移至全局范围。这样,您就不必在每次调用 main() 时重新定义它。

关于javascript - HTML5 逐帧动画(多个图像),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32431660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com