Controlling FPS with requestAnimationFrame
requestAnimationFrame has become the preferred method for smooth animations, but it can sometimes run at varying speeds. Here's a technique to ensure a consistent frame rate:
Throttle requestAnimationFrame to a Specific FPS
This method uses a conditional check to only execute the animation code when a specified FPS interval has elapsed.
Implementation:
Initialize Variables:
Start Animation:
Animation Loop:
Drawing Code:
Example Code:
<code class="javascript">var stop = false; var frameCount = 0; var fps, fpsInterval, startTime, now, then, elapsed; function startAnimating(fps) { fpsInterval = 1000 / fps; then = Date.now(); startTime = then; animate(); } function animate() { requestAnimationFrame(animate); now = Date.now(); elapsed = now - then; if (elapsed > fpsInterval) { then = now - (elapsed % fpsInterval); // Put your drawing code here } }</code>
This approach ensures that the animation runs at the specified FPS, regardless of the browser's rendering speed.
The above is the detailed content of How to Control FPS in Animations Using requestAnimationFrame?. For more information, please follow other related articles on the PHP Chinese website!