HTML canvas createPattern()Method

Canvas 对象参考手册Canvas Object

Image used:

Lamp

Example

Repeat the image in horizontal and vertical directions:

YourbrowserdoesnotsupporttheHTML5canvastag.

JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("lamp");
var pat=ctx.createPattern(img,"repeat");
ctx.rect(0,0,150,100);
ctx.fillStyle=pat;
ctx.fill();

Try it Yourself »

Browser Support

Internet ExplorerFirefoxOperaGoogle ChromeSafari

Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the createPattern() method.

Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.


Definition and Usage

The createPattern() method repeats the specified element in the specified direction.

The element can be an image, a video, or another <canvas> element.

The repeated element can be used to draw/fill rectangles, circles, lines, and so on.

JavaScript Syntax: context.createPattern(image,"repeat|repeat-x|repeat-y|no-repeat");

Parameter Values

Parameter Description
image Specifies the image, canvas, or video element to use as the pattern.  
repeat Default. The pattern is repeated both horizontally and vertically.
repeat-x The pattern is repeated only horizontally.
repeat-y The pattern is repeated only vertically.
no-repeat The pattern is displayed only once (no repetition).


Canvas 对象参考手册Canvas Object

Other Extensions