jeudi 25 décembre 2014

How do I at a fixed framerate with requestAnimationFrame? (See)


I know I know, this has been asked PLENTY of times. But the truth is, it doesn't work for me.


Let me give you some context, I'm trying to animate a simple rectangle in canvas, and I want to do it width requestAnimationFrame because obviously setTimeout or setInterval act as little minions of the devil and are not to be touched, along with their big bro, eval.


But you see, when you are trying to animate something, you need fixed timings, you just do. Let's say I want my square to go from a width of 100, to a final width of 200 over one second.


Well then I need a fixed framerate. For the sake of simplicity and smoothness like a baby's butt drowned in olive oil, that fixed framerate will be 60.


I found a great method to fix framerates with and applied it to my code, really happy, but it doesn't work, the animations last (at 60fps) double what they're supposed to!



function drawingFunc(){
requestAnimationFrame( drawingFunc );
var now = Date.now();
if( now - then >= refresh ){
then = now;
drawStuff();
}
}


--> I understand this is complicated so I created a commented JSFiddle illustrating my problem.


In it you will see what I'm talking about and you can also mess around with the values so you don't have to start from scratch. Here's an image with the results: results.png


--> You can download the whole file from goo.gl/ 0BIVc6 if you prefer to edit it in a better IDE.





Aucun commentaire:

Enregistrer un commentaire