I recently got into using the HTML5-requestAnimationFrame-API a lot on animation
ID: 646332 • Letter: I
Question
I recently got into using the HTML5-requestAnimationFrame-API a lot on animation-heavy websites, especially after seeing the Jank Busters talk. This seems to work pretty well and really improve performance in many cases.
Yet one question still persists for me: When wanting to use an animation that is NOT entirely calculated (think spritesheets for example) you will have to aim for a fixed frame rate. Of course one could go back to use setInterval again, but maybe there are other ways to tackle this.
The two ways I could think of using requestAnimationFrame with a fixed frame rate are:
var fps = 25; //frames per second
function animate(){
//actual drawing goes here
setTimeout(function(){
requestAnimationFrame(animate);
}, 1000 / fps)
}
animate();
or
var fps = 25; //frames per second
var lastExecution = new Date().getTime();
function animate(){
var now = new Date().getTime();
if ((now - lastExecution) > (1000 / fps)){
//do actual drawing
lastExecution = new Date().getTime();
}
requestAnimationFrame(animate);
}
animate();
Personally, I'd opt for the second option (the first one feels like cheating), yet it seems to be more buggy in certain situations.
Is this approach really worth it (especially at low frame rates like 12.5)? Are there things to be improved? Is there another way to tackle this?
Explanation / Answer
Your animation should be calculated even if that calculation is entirely a function of time. And at any given time you should be able to draw() an [animated] image and know that you're getting the right frame. You want something like this, but not necessarily this:
... Or whatever.