如何将requestAnimationframe限制为特定帧速率
演示以5 FPS的速度节流:http :
//jsfiddle.net/m1erickson/CtsY3/
此方法通过测试自执行最后一个帧循环以来的经过时间来工作。
代码的第一部分设置了一些用于计算经过时间的变量。
var stop = false;var frameCount = 0;var $results = $("#results");var fps, fpsInterval, startTime, now, then, elapsed;// initialize the timer variables and start the animationfunction startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; animate();}
这段代码是实际的requestAnimationframe循环,以您指定的FPS绘制。
// the animation loop calculates time elapsed since the last loop// and only draws if your specified fps interval is achievedfunction animate() { // request another frame requestAnimationframe(animate); // calc elapsed time since last loop now = Date.now(); elapsed = now - then; // if enough time has elapsed, draw the next frame if (elapsed > fpsInterval) { // Get ready for next frame by setting then=now, but also adjust for your // specified fpsInterval not being a multiple of RAF's interval (16.7ms) then = now - (elapsed % fpsInterval); // Put your drawing pre here }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)