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 discuss only 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]);
image

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.

repetition

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

repeat

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

repeat-x

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

repeat-y

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

no-repeat

The image is not tiled.

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

context.fillStyle = pattern;

or:

context.strokeStyle = pattern;

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

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

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.