HTML and CSS Reference
In-Depth Information
As mentioned, requestAnimationFrame is capped at 60 FPS (or rather, it's limited by the refresh rate of your web
browser), but as you have probably noticed there's no way to specify a delay. So what happens if you want to display
graphics at less than 60 FPS?
One possible solution to this problem involves calculating the delta between two timestamps. If the delta is
bigger that a given interval, which would basically dictate the framerate, you can draw the frame, leaving you with
enough processing power to perform more complex (and time-consuming) calculations.
Luckily, when you specify the callback to requestAnimationFrame , it will attempt to pass an additional
parameter with a timestamp that is relative to when the page has finished loading; that is, instead of being a
DOMHighResTimeStamp , it will attempt to pass a DOMTimeStamp . You can use this to your advantage by creating an
update loop that displays graphics at 30 FPS, as shown in Listing 8-5.
Listing 8-5. An Update Loop that Displays Graphics at 30 FPS
var fps = 30, // Define the maximum number of FPS
interval = 1000 / fps, // Calculate the interval in milliseconds
delta = 0, // Variable initialisation
previousTs = 0; // Variable initialisation
// Call the update loop for the first time
requestAnimationFrame(update);
function update(ts) {
// Calculate the delta between the previous timestamp and the new one
delta = ts - previousTs;
// Performing a calculation here means that it will be
// executed every 16.67 ms. at 60 frames per second
// Paint routine
if (delta > interval) {
// This bit will be executed only if it's bigger than the
// interval and therefore will be executed every 33.33 ms.
// at 30 frames per second (or the value of the "fps" variable)
// Set the previous timestamp, which will be used
// in the "next" loop.
// Subtract the difference between the delta and the interval
// to account for the time that it took the computer to
// process the function.
previousTs = ts - (delta % interval);
}
// Call requestAnimationFrame again
requestAnimationFrame(update);
}
 
Search WWH ::




Custom Search