HTML and CSS Reference
// 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)
// Paint the image on the canvas
// There's no need to go through all this logic on every frame
shouldRepaint = false;
// 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
Obviously, in order to repaint this background 60 times per second you would need one of two possible options,
either a faster machine or a better painting algorithm.
But what if you were using a much slower device (such as a smartphone)? While many people would consider
that to be impossible, it's always nice to have one more trick up your sleeve.
Let's suppose that besides the background, you also wanted to display a bouncing ball on your canvas. In that
case, there are two potential solutions. The first solution consists of handling the background and the animations
in two different viewports; therefore you would only need to clean and update the foreground canvas, leaving the
background canvas unchanged, as explained in Figure 8-10 . While it's certainly not very elegant, this solution is fit for
used in a scenario where the background won't be suffering any modifications. In such case, the background canvas
doesn't even need to be a canvas at all; it could be any other markup element that allows you to display an image
(such as a <div>).