How do you fill with a pattern on HTML5 canvas?

Use HTML5 canvas' createPattern method in JavaScript:

Select an image to be repeated to create a pattern (e.g. "pattern.png").

Pattern Image

Create a new image called image, set its source to "pattern.png" and set its onload event. Once the image is loaded use the context's method createPattern to create the pattern. The createPattern method takes two parameters: the image object and string that specifies the repeat type: "repeat", "repeat-x", "repeat-y" and "no-repeat". Set the context's fillStyle to the new pattern and using the context's fillRect to fill the pattern on the canvas.

var context = document.getElementById("canvas").getContext("2d");
var image = new Image();

function drawPattern() {
    context.fillStyle = context.createPattern(image, "repeat");
    context.fillRect(0, 0, 300, 300);

image.src = "images/pattern.png";
image.onload = drawPattern;

The canvas has the the example image repeated times in both x and y direction:

Related Articles