Animated Gradients

Before we leave the topic of text, we would like to introduce some animation into the mix. Everything you have seen so far in this chapter has been pretty much static. While text on HTML5 Canvas is really cool, it is not too far from what could be accomplished in standard HTML. Static text is static, and its utility when not being styled with CSS (again, the Canvas currently does not support CSS styling) might make you choose another solution for a pure text application.

However, animation is where the Canvas shows its utility beyond standard HTML. For this example, we will move away from Text Arranger and create some animated text by using only gradient fills. The gradient fills will “animate” by moving up in the text fill. The effect here is similar to what old video game and computer systems (especially those from Atari) used to create animated title screens.

Figure 3-12 shows what a single frame of the animation looks like on the Canvas.

Color cycle animation

Figure 3-12. Color cycle animation

The key to creating a gradient animation are the createLinearGradient() and gradient.addColorStop methods we discussed previously in this chapter, combined with the setTimeout() game loop functionality we developed in Chapter 1. First, we will set up a gradient “line” that represents the direction of the color gradient, and then we will create “color stops” that represent the colors in the gradient ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.