Game Development Reference
In-Depth Information
API usage
A general description and demonstration of each of the APIs used in the game are
given as follows. For an explanation of how each of the functionality was incorpor-
ated into the final game, look at the following code section. For the complete source
code for this game, check out the topic's page at the Packt Publishing website.
Before requestAnimationFrame was introduced, the main method developers
used to create animations in JavaScript was by using a timer to repeatedly call a
function that gradually updated attributes of the element(s) being animated. While
this is a straightforward method, what the browser provides through requestAnim-
ationFrame has a couple of added benefits. First of all, the browser uses a single
animation cycle to handle the rendering of a page, so any rendering we do using that
same cycle will result in a smoother animation, since the browser can optimize the
animation for us. Also, since the rendering would be done by the browser's internal
rendering mechanism, our animation would not run when the browser tab running
our animation is not shown. This way we don't waste battery life animating something
that is not even visible.
How to use it
Using requestAnimationFrame is very simple, and similar to setTimeout . We
call the requestAnimationFrame function on the global window object, passing
a callback function that is executed whenever the browser is ready to run another
animation cycle. When the callback is invoked, it is passed in a timestamp, which
is normally used inside the animation function we register with requestAnima-
tionFrame .
There are two common ways in which requestAnimationFrame is used, both
of which achieve the same result. In the first method, you define your animation
function with no references to requestAnimationFrame . Then, a second function
calls that animation function, followed by a call to requestAnimationFrame .
function myAnimationLoop(time) {
// 1. Perform the animation
myAnimation(time);
Search WWH ::




Custom Search