Exact time using RequestAnimationFrame

I have not yet found a lot of documentation on this. The general feeling that I get is that when implementing animations for the browser, it is better to use RequestAnimationFrame over the standard JavaScript swamp timers. I understand that timers are unreliable, and their resolution may vary depending on different browsers.

I looked at this point: https://gist.github.com/1114293#file_anim_loop_x.js

But I don’t understand how you can ensure that the animation goes through a certain time. For example, I could revive something from left to right for 2 seconds. Is it able to use RequestAnimationFrame or does it rob the target?

+6
source share
3 answers

Be that as it may, I had a similar problem recently, and I came up with an approach that combines rAF with .now () efficiency, which works very efficiently.

Im now allows you to do timers with an accuracy of 12 decimal places:

window.performance = window.performance || {}; window.performance.now = (function() { return performance.now || window.performance.mozNow || window.performance.msNow || window.performance.oNow || window.performance.webkitNow || function() { return new Date().getTime(); }; })(); 

http://jsfiddle.net/CGWGreen/9pg9L/

+3
source

RequestAnimationFrame is better in the following: you can draw when it will be most efficient. That is, RequestAnimationFrame can give better fps than just timers, but direct accurate time can be even less reliable. You should get the current time, compare it with the value from the previous frame and calculate the animation according to the amount of time that has passed since the last frame.

0
source

I would use time based animation. In each rAF iteration, you can measure the temporal relationship to the previous iteration. Knowing this delta time and the "distance" in pixels, you can calculate the necessary speed to get 2 seconds.

This article from Mozilla Hacks discusses various considerations for animating at a constant speed (pixel / second). Here is a snippet that explains the basic concept:

 animLoop(function( deltaT ) { elem.style.left = ( left += 10 * deltaT / 16 ) + "px"; if ( left > 400 ) { return false; } }); 
0
source

Source: https://habr.com/ru/post/910770/


All Articles