Filling Shapes with Gradients

There are two basic options for creating gradient fills on the canvas: linear and radial. A linear gradient creates a horizontal, vertical, or diagonal fill pattern; the radial variety creates a fill that “radiates” from a central point in a circular fashion. Let’s look at some examples of each.

Linear gradients

Linear gradients come in three basic styles: horizontal, vertical, and diagonal. We control where colors change in our gradient by setting color stops at points along the length of the object we want to fill.

Linear horizontal gradients

Example 2-14 creates a simple horizontal gradient, as shown in Figure 2-23.

Example 2-14. A linear horizontal gradient

function drawScreen() {

      // horizontal gradient values must remain 0
      var gr = context.createLinearGradient(0, 0, 100, 0);

      // Add the color stops.
      gr.addColorStop(0,'rgb(255,0,0)');
      gr.addColorStop(.5,'rgb(0,255,0)');
      gr.addColorStop(1,'rgb(255,0,0)');

      // Use the gradient for the fillStyle.
      context.fillStyle = gr;
      context.fillRect(0, 0,100,100);

   }
A linear horizontal gradient

Figure 2-23. A linear horizontal gradient

To create the horizontal gradient, we must first create a variable (gr) to reference the new gradient. Here’s how we set it:

var gr = context.createLinearGradient(0,0,100,0);

The four parameter values in the createLinearGradient method call are the top-left x and y coordinates to start the gradient, as well as the two bottom-right ...

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.