所以,我正在制作一个使用 Javascript
的动画(不是在网站/网页上!)。对于动画,我使用 requestAnimationFrame
而不是 setInterval
,因为 setInterval
不能很好地满足我的需要。
但是,尽管 requestAnimationFrame
在性能良好的设备上运行良好,但速度较慢的设备无法跟上标准的 60 FPS,从而减慢了整个动画时间。
有没有一种方法可以让动画在一个时间范围内工作,并让 FPS 根据它的保持情况而变化?也欢迎其他想法。
(注意,我真的不想发布代码,请相信我的话。我只是想要想法)
最佳答案
看看这个演示:http://jsfiddle.net/q7ckebmh/
function Animate(id, useTime){
var can = document.getElementById(id),
ctx = can.getContext('2d'),
wid = can.width,
hei = can.height,
lst = Date.now(),
rps = 2*Math.PI,
step = rps/60, // Expecting 60fps
ang = 0;
(function draw(){
var dif = Date.now() - lst; // Milliseconds since last we drew.
lst = Date.now();
if (useTime) step = rps * dif/1000; // Allows for variable fps
ang += step; // Increment our placeholder. In the
// case where step is constant, this
// ends up looking "slow" when we
// have less than 60fps.
ctx.clearRect(0,0,wid,hei);
ctx.beginPath();
ctx.arc(wid/2 + Math.cos(ang)*50,hei/2 + Math.sin(ang)*50,
10,0,2*Math.PI);
ctx.fill();
requestAnimationFrame(draw);
})();
}
Animate('can1', false);
Animate('can2', true);
您会注意到,如果您调整帧的大小,第一个动画会因为跳过动画帧而变慢。
第二个动画似乎并没有减慢速度,因为它基于圆圈的位置自上次调用以来的时间。它看起来确实有点起伏不定,但位置始终是正确的。
关于javascript - requestAnimationFrame 在弱机器上运行缓慢。变通?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14508085/