Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Fundamentally, implementing animations with Canvas is simple: You continuously update and draw whatever you are animating. For example, the application shown in Figure 5.1 continuously animates three discs.
Figure 5.1. Basic animation
That continuous updating and redrawing is referred to as the animation loop, and it’s central to every animation. Let’s see how it works.
Animations are continuous loops, but it’s not possible to implement a continuous loop, at least not in the traditional sense, in JavaScript running in a browser. For instance, Example 5.1 is valid JavaScript, but it will lock up any respectable browser.
The while loop in Example 5.1 is an endless loop. Because browsers run JavaScript on the main thread, that endless loop will lock up the browser, including the animation. Instead, you must let the browser breathe, by periodically giving it control for short amounts of time.