Game Development Reference
In-Depth Information
// 2. Register with request animation frame
requestAnimationFrame(myAnimationLoop);
}
function myAnimation(time) {
// Perform animation here
}
The second pattern that is commonly used is very similar, except that it only includes
the main animation function. That function itself takes care of calling requestAn-
imationFrame when needed.
function myAnimation(time) {
// 1. Perform the animation
myAnimation(time);
// 2. Register with request animation frame
requestAnimationFrame(myAnimationLoop);
}
The reason that the time argument is useful is, because most of the time, you want
the animation to run more or less at the same rate on different computers. re-
questAnimationFrame attempts to run as close to 60 times per second as pos-
sible. However, based on the code you execute inside it, that rate may drop signific-
antly. Obviously, faster hardware would be able to execute your code much faster,
and thus, display it to the screen more often than some slower hardware would. In
order to make up for this possibility, we can use actual time to control how often the
animation code runs. This way, we can specify a cap refresh rate, which, if a particu-
lar computer is able to run faster than this rate, can simply slowdown that computer,
and all users experience about the same animation.
One possible implementation of this technique is shown in the following steps. Al-
though it may seem like a lot of steps, the concept is really quite simple. The gist of
it is this: we set two variables, one that keeps track of the cap speed that the anim-
ation will run (measured in frames per second ( fps )), and the other keeps track of
when the last time was, that a frame was rendered. Then, whenever the animation
Search WWH ::




Custom Search