现在看来,requestAnimationFrame
实际上是一种让事物动画化的方式。它在很大程度上对我来说工作得很好,但现在我正在尝试做一些画布动画,我想知道:有什么方法可以确保它以特定的fps运行吗?我知道rAF的目的是为了使动画始终流畅,我可能会冒着让我的动画断断续续的风险,但现在它似乎以截然不同的速度随意运行,我想知道是否有某种方法可以克服这一点。
我会使用setInterval
,但我想要rAF提供的优化(特别是当选项卡处于焦点时自动停止)。
如果有人想看我的代码,它很可能是:
animateFlash: function() {
ctx_fg.clearRect(0,0,canvasWidth,canvasHeight);
ctx_fg.fillStyle = 'rgba(177,39,116,1)';
ctx_fg.strokeStyle = 'none';
ctx_fg.beginPath();
for(var i in nodes) {
nodes[i].drawFlash();
}
ctx_fg.fill();
ctx_fg.closePath();
var instance = this;
var rafID = requestAnimationFrame(function(){
instance.animateFlash();
})
var unfinishedNodes = nodes.filter(function(elem){
return elem.timer < timerMax;
});
if(unfinishedNodes.length === 0) {
console.log("done");
cancelAnimationFrame(rafID);
instance.animate();
}
}
其中Node.drawFlash()只是一些代码,它根据计数器变量确定半径,然后绘制一个圆。
发布于 2016-08-25 10:09:38
我建议将您对requestAnimationFrame
的调用包装在setTimeout
中
const fps = 25;
function animate() {
// perform some animation task here
setTimeout(() => {
requestAnimationFrame(animate);
}, 1000 / fps);
}
animate();
您需要从setTimeout
内部调用requestAnimationFrame
,而不是相反,因为requestAnimationFrame
将您的函数安排为在下一次重新绘制之前运行,如果您使用setTimeout
进一步延迟更新,您将错过该时间窗口。然而,反之亦然,因为您只是在发出请求之前等待了一段时间。
发布于 2018-01-06 14:51:03
如何轻松调节到特定的FPS:
// timestamps are ms passed since document creation.
// lastTimestamp can be initialized to 0, if main loop is executed immediately
var lastTimestamp = 0,
maxFPS = 30,
timestep = 1000 / maxFPS; // ms for each frame
function main(timestamp) {
window.requestAnimationFrame(main);
// skip if timestep ms hasn't passed since last frame
if (timestamp - lastTimestamp < timestep) return;
lastTimestamp = timestamp;
// draw frame here
}
window.requestAnimationFrame(main);
来源:A Detailed Explanation of JavaScript Game Loops and Timing by Isaac Sukin
发布于 2020-04-01 03:17:00
var time = 0;
var time_framerate = 1000; //in milliseconds
function animate(timestamp) {
if(timestamp > time + time_framerate) {
time = timestamp;
//your code
}
window.requestAnimationFrame(animate);
}
https://stackoverflow.com/questions/19764018
复制相似问题