5.14 Animations 169
Figure 5.39 HSL colors for multicolored spheres animation
Then the sphere is drawn as a circle with the defined gradient. Embedding in
context.save() and context.restore() ensures that the temporary displace-
ment with translate() is not applied to the subsequent circles. Now the func-
tion drawCircles() is complete, and we can draw a first set of spheres and then
move on to the timer.
About 15 lines are sufficient to implement starting and stopping the animation
via an onclick event listener. With the first click on the canvas, we start the ani-
mation with window.setInterval() and save the unique interval ID in the vari-
able running. Times are specified in milliseconds for window.setInterval(), so
we need to convert the beats per minute accordingly in the variable pulse.
Once the animation is running, the unique interval ID is assigned to the vari-
able running, and with the next click, we can interrupt it using window.
clearInterval(running). If we then set running back to null, the next click on
the canvas signals: no animation is running. In this case, we restart and the fun
starts over.
5.14.2 Playing a Video with “drawImage()”
As you already know from section 5.7, Embedding Images, an HTMLVideoElement
can also be used as a source for drawImage(). But if you are hoping that videos
embedded in this way will play automatically, you will be disappointed, because
the logic for this must be implemented fully in JavaScript. This is not difficult,
as you can see from the final Canvas animation example—an extension of our
Yosemite National Park postcard in Figure 5.25. Instead of the static image sec-
tion with El Capitan, we now place a dynamic video into the top-right corner,
offering a 360° panoramic view from Taft Point. While the video is playing, ten
small snapshots of the running video appear as a gallery along the bottom of the
canvas. After the end of the video, you can see the picture shown in Figure 5.40.