"Si un ouvrier veut bien faire son travail, il doit d'abord affûter ses outils." - Confucius, "Les Entretiens de Confucius. Lu Linggong"
Page de garde > La programmation > How can I use RequestAnimationFrame to stabilize my animation\'s frame rate (FPS)?

How can I use RequestAnimationFrame to stabilize my animation\'s frame rate (FPS)?

Publié le 2024-11-08
Parcourir:975

How can I use RequestAnimationFrame to stabilize my animation\'s frame rate (FPS)?

RequestAnimationFrame Fps Stabilization

RequestAnimationFrame (rAF) has become prevalent for animations, offering smooth and efficient execution. However, controlling the frame rate (FPS) to ensure consistency can be challenging.

Throttling rAF to a Specific FPS

To throttle rAF to a specific FPS, you can leverage time elapsed since the last frame execution. Your drawing code will execute only when your desired FPS interval has elapsed.

Code Snippet

Initialize timer variables and start the animation:

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();
}

The rAF loop for drawing at your specified FPS:

function animate() {

    requestAnimationFrame(animate);

    now = Date.now();
    elapsed = now - then;

    if (elapsed > fpsInterval) {
        then = now - (elapsed % fpsInterval);
        // Your drawing code goes here
    }
}

By incorporating this logic, you can effectively throttle rAF to achieve a desired FPS, ensuring consistent animations that meet your specific requirements.

Dernier tutoriel Plus>

Clause de non-responsabilité: Toutes les ressources fournies proviennent en partie d'Internet. En cas de violation de vos droits d'auteur ou d'autres droits et intérêts, veuillez expliquer les raisons détaillées et fournir une preuve du droit d'auteur ou des droits et intérêts, puis l'envoyer à l'adresse e-mail : [email protected]. Nous nous en occuperons pour vous dans les plus brefs délais.

Copyright© 2022 湘ICP备2022001581号-3