Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Canvas Interval vs RequestAnimationFrame

So, maybe total brainfart here. The syntax for setInterval() is pretty clear. Do something every x miliseconds. How is this best translated to using the requestAnimationFrame() ?

I have about 300 objects and each is supposed to perform an animation sequence at a certain interval (every 8, 6, 2, etc seconds)? How can I best accomplish this using requestAnimationFrame() which gets called ~60 times a second? There is probably an easy answer, I just, for the life of me, can't figure it out.

like image 691
David M. Avatar asked Aug 13 '12 22:08

David M.


1 Answers

To force requestAnimationFrame to stick to a specific FPS you can use both at once!

var fps = 15;
function draw() {
    setTimeout(function() {
        requestAnimationFrame(draw);
        // Drawing code goes here
    }, 1000 / fps);
}

A little weird, but noth the most confusing thing in the world.

You can also use requestAnimationFrame not with FPS but with elapsed time in order to draw objects that need to be updated based on the time difference since the last call:

var time;
function draw() {
    requestAnimationFrame(draw);
    var now = new Date().getTime(),
        dt = now - (time || now);
 
    time = now;
 
    // Drawing code goes here... for example updating an 'x' position:
    this.x += 10 * dt; // Increase 'x' by 10 units per millisecond
}

These two snippets are from this fine article, which contains additional details.

Good question by the way! I don't think I've seen this answered on SO either (and I'm here way too much)

like image 127
Simon Sarris Avatar answered Sep 24 '22 16:09

Simon Sarris