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.
CanvasPattern ctx.createPattern(image, repetition);
imageCanvasImageSource to be used as the pattern's image. It can be any of the following: HTMLImageElement (<img>)SVGImageElement (<image>)HTMLVideoElement (<video>, by using the capture of the video)HTMLCanvasElement (<canvas>)ImageBitmapOffscreenCanvasrepetitionDOMString indicating how to repeat the pattern's image. Possible values are: "repeat" (both directions)"repeat-x" (horizontal only)"repeat-y" (vertical only)"no-repeat" (neither direction)repetition is specified as an empty string ("") or null (but not undefined), a value of "repeat" will be used.CanvasPatternThis 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.
<canvas id="canvas" width="300" height="300"></canvas>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
img.onload = function() {
var pattern = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, 300, 300);
};
| Specification | Status | Comment |
|---|---|---|
| HTML Living Standard The definition of 'CanvasRenderingContext2D.createPattern' in that specification. | Living Standard |
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | Yes | 12 | Yes | Yes | Yes | Yes |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
null or undefined image correctly throws a TYPE_MISMATCH_ERR exception.null for the repetition parameter is now allowed and results in the repetition being set to "repeat" (bug 762657).CanvasRenderingContext2D
CanvasPattern
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createPattern