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]);

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 fillStyle and strokeStyle 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 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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.