js requestAnimationFrame固定每秒60帧数
时间: 2023-11-30 15:43:01 浏览: 133
根据提供的引用内容,requestAnimationFrame并不能固定每秒60帧数,它只是在浏览器重绘之前调用回调函数,以便进行动画渲染等操作。如果要固定每秒60帧数,可以在回调函数中使用时间戳来计算每一帧之间的时间间隔,从而控制动画的帧率。
以下是一个使用requestAnimationFrame实现固定每秒60帧数的例子:
```javascript
let lastTime = 0;
let vendors = ['webkit', 'moz'];
for (let i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) {
window.requestAnimationFrame = window[vendors[i] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[i] + 'CancelAnimationFrame'] || window[vendors[i] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function(callback, element) {
let currTime = new Date().getTime();
let timeToCall = Math.max(0, 16 - (currTime - lastTime));
let id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}
let fps = 60;
let interval = 1000 / fps;
let then = Date.now();
let startTime = then;
let endTime = startTime + 5000;
function draw() {
let now = Date.now();
let elapsed = now - then;
if (now < endTime) {
requestAnimationFrame(draw);
}
if (elapsed > interval) {
then = now - (elapsed % interval);
// 在这里进行动画渲染等操作
}
}
requestAnimationFrame(draw);
```
阅读全文