gpt4 book ai didi

javascript - 通过添加 eventListener 取消 Canvas 动画

转载 作者:行者123 更新时间:2023-11-28 17:56:06 25 4
gpt4 key购买 nike

当我调整浏览器大小时,我试图从起点重置矩形动画,代码如下:

/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize",function(){
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
//cancelAnimationFrame(timeID)
//theRect();
});

/*drawing the rectangle*/
var x = 0,y = canvas.height - 100,w = 100, h = 100,dx=1;

function theRect(){
ctx.fillStyle = "lightblue";
ctx.fillRect(x,y,w,h)
x+=dx;
if(x+w>canvas.width/2 || x<0){
dx=-dx;
}
}

/*start animation*/

function animate(){
ctx.clearRect(0,0,canvas.width,canvas.height);
theRect();
requestAnimationFrame(animate);

}
//var timeID = requestAnimationFrame(animate)

animate();

我在想,如果每次浏览器调整大小时,矩形都必须重置为起点 ctx.fillRect(0,canvas.height-100,100,100)并继续其动画。

所以我最初解决这个问题的方法是使用 cancelAnimationFrame()此方法首先终止动画并在我的 eventlistener 中再次调用此函数因此,每次触发该事件时,动画都会停止并再次运行。

但是cancellAnimationFrame()函数需要目标动画时间ID,而我的animate()中没有办法跟踪这个时间ID函数,因为如果我打电话 var timeID = requestionAnimationFrame(animate)我的浏览器会出现巨大的延迟峰值

我越想修改得越多,我就会对此感到困惑,所以我的问题是:

1,使用 cancelAnimationFrame 是否明智?这是重置我的动画的第一步吗?

2、有没有其他好的方法可以达到这个“重置”的目的?

有人可以帮我解决这个问题吗?提前致谢。

最佳答案

在这种情况下,根本不需要使用 cancelAnimationFrame() 函数。

您只需在窗口大小调整时相应地更改/重置 xy 变量的值(位置),这将重置矩形起始位置/点。

由于 animate 函数以递归方式运行,因此会更改任何变量 (在 animate 函数内部使用) 值立即生效。

/*from basic setup*/
canvas = document.getElementById("myCanvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
ctx = canvas.getContext("2d");

/*drawing the rectangle*/
var x = 0,
y = canvas.height - 100,
w = 100,
h = 100,
dx = 1;

/*the "resize" event and the reset function should be triggered */
window.addEventListener("resize", function() {
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
x = 0; //reset starting point (x-axis)
y = canvas.height - 100; //reset starting point (y-axis)
});

function theRect() {
ctx.fillStyle = "lightblue";
ctx.fillRect(x, y, w, h);
x += dx;
if (x + w > canvas.width / 2 || x < 0) {
dx = -dx;
}
}

/*start animation*/
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
theRect();
requestAnimationFrame(animate);
}
animate();
body{margin:0;overflow:hidden}
<canvas id="myCanvas"></canvas>

另请参阅 demo on JSBin

关于javascript - 通过添加 eventListener 取消 Canvas 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44402027/

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