Home  >  Article  >  Web Front-end  >  How to Control FPS in Animations Using requestAnimationFrame?

How to Control FPS in Animations Using requestAnimationFrame?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 14:43:41724browse

How to Control FPS in Animations Using requestAnimationFrame?

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:

  1. Initialize Variables:

    • Create variables for stop, frameCount, elapsed time, start time, and FPS interval.
  2. Start Animation:

    • Initialize these variables and invoke the animate() function to start the loop.
  3. Animation Loop:

    • Calculate the elapsed time since the last loop using Date.now().
    • If elapsed is greater than the fpsInterval, draw the next frame.
    • Adjust then to account for the difference between the FPS interval and RAF's default interval.
  4. Drawing Code:

    • Place your drawing code within the conditional check (if elapsed > fpsInterval).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn