The CanvasRenderingContext2D.createPattern()
method of the Canvas 2D API creates a pattern using the specified image and repetition. This method returns a CanvasPattern
.
This method doesn't draw anything to the canvas directly. The pattern it creates must be assigned to the CanvasRenderingContext2D.fillStyle
or CanvasRenderingContext2D.strokeStyle
properties, after which it is applied to any subsequent drawing.
createPattern(image, repetition)
CanvasPattern
-
An opaque object describing a pattern.
If the image
is not fully loaded (HTMLImageElement.complete
is false
), then null
is returned.
This example uses the createPattern()
method to create a CanvasPattern
with a repeating source image. Once created, the pattern is assigned to the canvas context's fill style and applied to a rectangle.
The original image looks like this:
HTML
<canvas id="canvas" width="300" height="300"></canvas>
JavaScript
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const img = new Image();
img.src = "canvas_createpattern.png";
img.onload = () => {
const pattern = ctx.createPattern(img, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 300, 300);
};
In this example we create a pattern from the contents of an offscreen canvas. We then apply it to the fill style of our primary canvas, and fill that canvas with the pattern.
JavaScript
const patternCanvas = document.createElement("canvas");
const patternContext = patternCanvas.getContext("2d");
patternCanvas.width = 50;
patternCanvas.height = 50;
patternContext.fillStyle = "#fec";
patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height);
patternContext.arc(0, 0, 50, 0, 0.5 * Math.PI);
patternContext.stroke();
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const pattern = ctx.createPattern(patternCanvas, "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, canvas.width, canvas.height);
document.body.appendChild(canvas);
Result