O'Reilly logo

HTML5 Canvas by Jeff Fulton, Steve Fulton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Text with Gradients and Patterns

We’ve already explored the fillColor and strokeColor properties of the Canvas context by setting those value to CSS-compliant colors. However, those very same properties can be set to refer to a few other objects defined in the Canvas API to create some stunning text effects. The objects are:

Linear gradient

A linear color gradient with two or more colors

Radial gradient

A circular color gradient with two or more colors

Image pattern

An Image object used as a fill pattern

Linear Gradients and Text

To create a linear gradient, make a call to the context’s createLinearGradient() method to create a Gradient object. The createLinearGradient() method accepts four parameters that all define the line of the linear gradient. The x0 and y0 parameters are the starting point of the line, and x1 and y1 represent the ending point of the line:

var gradient = context.createLinearGradient( [x0],[y0],[x1],[y1]);

For example, if you want to create a linear gradient that starts at the beginning of the text (located at 100,100), and has an endpoint that is the width of your text as displayed on the canvas, you might write the following code:

var metrics = context.measureText(message);
var textWidth = metrics.width;
var gradient = context.createLinearGradient(100, 100, textWidth, 100);

After you have created the line that represents the gradient, you need to add colors that will form the gradations of the gradient fill. This is done with the addColorStop() method, which requires two arguments: offset and color:


This is the offset on the gradient line to start the color gradation. The entire gradient is represented by the numbers between 0.0 and 1.0. The offset will be a decimal that represents a percentage.


A valid CSS color in the format “#RRGGBB”.

So, if you want black to be the first color in the gradient, and then red to be the second color that starts halfway down the gradient line, you would create two calls to addColorStop():

gradient.addColorStop(0, "#000000");
gradient.addColorStop(.5, "#FF0000");


If you fail to add colors with addColorStop(), the text will be rendered invisible.

The results are shown in Figure 3-9.

Text with linear gradient applied

Figure 3-9. Text with linear gradient applied

Radial Gradients and Text

A radial gradient is created much like a linear gradient, except that it represents a cone—not a line. The cone is created by defining the center points and the radii of two different circles when calling the createRadialGradient() function of the Canvas context:

var gradient = context.createRadialGradient([x0],[y0],[radius0],[x1],[y1],[radius1]);

Let’s say you want to create a radial gradient based on a cone. It starts with a circle that has its center point at 100,100 and a radius of 20, and ends at a circle with its center point at 200,100 and a radius of 5. The code would look like this:

var gradient = context.createRadialGradient(100,100,20,200,100,5);

Adding color stops to a radial gradient works the same as with a linear gradient, except the color moves along the cone instead of the line:

gradient.addColorStop(0, "#000000 ");
gradient.addColorStop(.5, "#FF0000");

Image Patterns and Text

Another option for filling text on HTML5 Canvas is to use an Image object. We will devote all of Chapter 4 to using the Image API, so here we will only discuss the basics of how to use one as a pattern for a text fill.

To create an image pattern, call the createPattern() method of the Canvas context, passing a reference to an Image object, and an option for repetition:

var pattern = context.createPattern([image], [repetition]);

A valid Image object that has been loaded with an image by setting the pattern.src property and waiting for the image to load by setting an event listener for the Image onload event. The Canvas specification also allows for a video element or another <canvas> to be used here as well.


The “tiling” of the image. This can have one of four values:


The image is tiled on both the x and y axes.


The image is tiled only on the x-axis (horizontally).


The image is tiled only on the y-axis (vertically).


The image is not tiled.

To use the image pattern, apply it to the fillColor and strokeColor properties of the context, just as you would apply a color:

context.fillStyle = pattern;


context.strokeStyle = pattern;

For example, to load an image named texture.jpg and apply it to the fillStyle so that it tiles on both the x and y axes, you would write code like this:

var pattern = new Image();
pattern.src = "texture.jpg"
pattern.onload = function() {
 var pattern = context.createPattern("texture.jpg", "repeat");
 context.fillStyle = pattern;

Handling Gradients and Patterns in Text Arranger

Text Arranger 3.0 includes many changes that were implemented to support using gradients and image patterns with text on HTML5 Canvas. To see these changes in action, we first need to make sure that we have preloaded the texture.jpg image, which we will use for the context.createPattern() functionality. To do this, we will create a new function named eventAssetsLoaded() that we will set as the event handler for the onload event of the Image object that will hold the pattern. When that image has loaded, we will call canvasApp() in the same way we called it from eventWindowLoaded():

function eventWindowLoaded() {
   var pattern = new Image();
   pattern.src = "texture.jpg";
   pattern.onload = eventAssetsLoaded;

function eventAssetsLoaded() {



We are not going to use the pattern variable we created in this function, as it does not have scope in the canvasApp() function. We are merely using it to make sure that the image is available before we use it.

In the canvasApp() function, we will create three variables to support this new functionality. fillType describes how the text will be filled (a regular color fill, a linear gradient, a radial gradient, or a pattern). The textColorFill2 variable is the second color we will use for the gradient color stop. Finally, the pattern variable holds the Image object we preloaded, which we now need to create an instance of in canvasApp():

var fillType = "colorFill";
var textFillColor2 = "#000000";
var pattern = new Image();
pattern.src = "texture.jpg";

Now, let’s jump to the HTML of our <form>. Since we have created different ways to fill the text we are displaying, we need to build a selection that allows for this choice. We will create a <select> box with the id of fillType for this purpose:

Fill Type: <select id="fillType">
  <option value="colorFill">Color Fill</option>
  <option value="linearGradient">Linear Gradient</option>
  <option value="radialGradient">Radial Gradient</option>
  <option value="pattern">pattern</option>

We need to add a second color selection that we can use for the gradient fills. We will use the jsColor picker and the id textColorFill2:

Text Color 2: <input class="color" id="textFillColor2" value ="000000"/>

Back in canvasApp(), we need to create the event listeners for our two new form elements:

   formElement = document.getElementById("textFillColor2");
   formElement.addEventListener('change', textFillColor2Changed, false);

   formElement = document.getElementById("fillType");
   formElement.addEventListener('change', fillTypeChanged, false);

We also need to create the associated event handler functions for the new form elements:

function textFillColor2Changed(e) {
      var target = e.target;
      textFillColor2 = "#" + target.value;

   function fillTypeChanged(e) {
      var target = e.target;
      fillType = target.value;

We need to add support to drawScreen() for this new functionality. First, we use the measureText() method of the context to get the width of the text, which we will use to create the gradients:

var metrics = context.measureText(message);
var textWidth = metrics.width;

Then, we need to decide how to format our “color” for the fillStyle or strokeStyle of the context. In this instance, it can be a CSS color, a gradient, or an image pattern; the list below provides more information.

Color fill

If we are doing a simple color fill, we operate just like in previous versions of Text Arranger. All we need to do is make tempColor equal to the value of y.

Linear gradient

For the linear gradient, we need to decide what line we are going to create for the gradient. Our line will start at the beginning of the text (xPosition-textWidth/2 because the text uses the center alignment), and runs horizontally to the end of the text (textWidth). We also add two color stops (at 0 and 60%)—the colors are textFillColor1 and textFillColor2.

Radial gradient

For the radial gradient, we are going to create a cone that starts at the center of the text (xPosition,yPosition) with a radius the size of the font (fontSize). The cone will extend horizontally the width of the text (textWidth) with a radius of 1.


For this option, we create a pattern using the pattern image variable we previously created. We designate it to repeat so it will tile horizontally and vertically.

Here’s the code:

var tempColor;
if (fillType == "colorFill") {
   tempColor = textFillColor;
} else if (fillType == "linearGradient") {
   var gradient = context.createLinearGradient(xPosition-
       textWidth/2, yPosition, textWidth, yPosition);
   tempColor = gradient;
} else if (fillType == "radialGradient") {
   var gradient = context.createRadialGradient(xPosition, yPosition, 
       fontSize, xPosition+textWidth, yPosition, 1);
   tempColor = gradient;
} else if (fillType == "pattern") {
  var tempColor = context.createPattern(pattern,"repeat");
} else {
   tempColor = textFillColor;

Now, when we set our fillStyle or strokeStyle, we use tempColor instead of textFillColor. This will set the proper text fill choice that will be displayed on the canvas, as shown in Figure 3-10:

context.fillStyle = tempColor;
Text with image pattern applied

Figure 3-10. Text with image pattern applied

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required