gpt4 book ai didi

javascript - Internet Explorer 中的动画卡顿

转载 作者:行者123 更新时间:2023-12-03 10:12:22 25 4
gpt4 key购买 nike

该问题似乎仅与 Internet Explorer 有关。当该示例在IE中使用jsfiddle运行时,运行顺利。如果在我的本地计算机上尝试并使用 IE 打开,则会出现卡顿。可能是什么问题?

更新:如果删除 setTimeout,它不会卡顿,但如果我通过添加 setTimeout 将其强制为 60 帧,它就会卡顿。我需要将其强制为 60 帧/秒,并且至少运行流畅。

The code in jsfiddle

// Check if canvas exists and get the context of the canvas
var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');

// Add width and height of the canvas
var width = 640, height = 480;

// Make the canvas width and height as the variables
canvas.width = width, canvas.height = height;

rect = {
x: 0,
y: 0,
width: 100,
height: 100
}

ctx.fillStyle = 'red';
ctx.fillRect(rect.x,rect.y,rect.width,rect.height);

function animate(){
setTimeout(function(){
rect.x += 5;

ctx.fillStyle = 'red';
ctx.clearRect ( 0 , 0 , canvas.width, canvas.height );
ctx.fillRect(rect.x,rect.y,rect.width,rect.height);

if(rect.x <= 200){
requestID = requestAnimationFrame(animate);
}
}, 1000 / 60);
}

requestAnimationFrame(animate);

最佳答案

结合 requestAnimationFramesetTimeout 进行绘画是没有意义的。也许您希望以 60 fps 的稳定速率更新动画,但这并不意味着您需要以恰好 60 fps 的速率重新绘制。

将动画更新与动画绘制分开,您的问题将得到解决:

function paintAnimation() {
ctx.fillStyle = 'red';
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
requestAnimationFrame(paintAnimation);
}
requestAnimationFrame(paintAnimation);

function updateAnimation() {
rect.x += 5;
if (rect.x <= 200)
setTimeout(updateAnimation, 1000 / 60);
}
updateAnimation();

See JSFiddle

关于javascript - Internet Explorer 中的动画卡顿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052103/

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