HTML and CSS Reference
In-Depth Information
window[vendors[x]+'CancelAnimationFrame'] ||
window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime +
timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
As you can see, if the nonvendor-prefixed version of
requestAnimationFrame
isn't available, the code
loops through each of the potential vendor-specific prefixes and uses that prefix as the nonprefixed version.
If that fails, the code approximates
requestAnimationFrame
and
cancelAnimationFrame
using
setTimeout
and
cancelTimeout
. These polyfilled methods, because they don't have native browser sup-
port, do suffer from the drawbacks previously mentioned, but they are the best you can use.
Adding the Optimized Game Loop to Quintus
Having created a consistent polyfill to an optimized timer method, up next is creating the game loop itself.
The traditional game loop has two main pieces that execute each frame: update and render. The update piece
is responsible for stepping the game logic through a small chunk of time, handling any user input, motion, and
collisions between objects and updating each game object to a consistent state.
Next, the game needs to render itself onto the screen. How the rendering step is done depends on how your
game is built. For Canvas-based games, you usually want to clear the entire Canvas and then redraw all the ne-
cessary sprites on to the page, for CSS and SVG games. Provided you updated the properties of the objects on
the page correctly, your job is actually doneāthe browser takes care of moving and updating the objects.
Armed with this knowledge, you can add a game loop method to Quintus and
pause
and
unpause
meth-
Listing 9-5:
Adding a game loop
Q.gameLoop = function(callback) {
Q.lastGameLoopFrame = new Date().getTime();
Q.gameLoopCallbackWrapper = function(now) {
Q.loop = requestAnimationFrame(Q.gameLoopCallbackWrapper);