HTML5 Guidelines for Web Developers

(coco) #1

166 Chapter 5—Canvas


This technique is excellent where transformations or clipping masks are con-
cerned. And for shadow effects, it is much easier to reset the four shadow com-
ponents back to their default values with context.save() and context.restore()
than setting each component individually. For the animations we will discuss
next, context.save() and context.restore() are practically indispensable.

5.14 Animations


Unlike SVG or SMIL animations, Canvas animations are done purely manually.
The ingredients are a function for drawing plus a timer calling it in regular inter-
vals. JavaScript offers window.setInterval() for this purpose; the rest is up to the
imagination of the Canvas programmer.

5.14.1 Animation with Multicolored Spheres


This is our animation premiere: Spheres of different colors appear in random
places on the canvas, fade slowly, and are covered by other spheres. The anima-
tion speed should correspond to an adult’s resting pulse of about 60 beats per
minute. As an additional feature, we want to be able to stop or restart the anima-
tion by clicking on the canvas.
About 50 lines of JavaScript code are sufficient. But before turning to the analysis
of Listing 5.3, let’s look at a static screen shot of the result in Figure 5.38.
Free download pdf