Home > Web Front-end > JS Tutorial > body text

How to Control FPS in Animations Using requestAnimationFrame?

Susan Sarandon
Release: 2024-10-30 14:43:41
Original
778 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template