The CanvasRenderingContext2D
.createPattern()
method of the Canvas 2D API creates a pattern using the specified image (a CanvasImageSource
). It repeats the source in the directions specified by the repetition argument. This method returns a CanvasPattern
.
CanvasPattern ctx.createPattern(image, repetition);
image
CanvasImageSource
to be used as the image to repeat. It can be an: HTMLImageElement
(<img>
)HTMLVideoElement
(<video>
, by using the capture of the video)HTMLCanvasElement
(<canvas>
)CanvasRenderingContext2D
ImageBitmap
ImageData
Blob
repetition
DOMString
indicating how to repeat the image. Possible values are: "repeat"
(both directions)"repeat-x"
(horizontal only)"repeat-y"
(vertical only)"no-repeat"
(neither)''
) or null
(but not undefined
), repetition will be "repeat".CanvasPattern
createPattern
methodThis is just a simple code snippet which uses the createPattern
method to create a CanvasPattern
with the specified image and repetition. Once created, you can use the CanvasPattern.setTransform()
method to transform the pattern. The pattern gets applied if you set it as the current fillStyle
and gets drawn onto the canvas when using the fillRect()
method, for example.
<canvas id="canvas"></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, 400, 400); };
Edit the code below and see your changes update live in the canvas:
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.createPattern' in that specification. | Living Standard |
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
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