English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML reference manual

HTML tag大全

HTML canvas createPattern() method

createPattern() is Canvas 2The createPattern() method is used to create a pattern with a specified image (CanvasImageSource). It repeats the original image in the specified direction through the repetition parameter. This method returns a CanvasPattern object. CanvasPattern ctx.createPattern(image, repetition);

HTML canvas reference manual

Image used:

Online Example

Repeat image in horizontal and vertical directions:

Your browser does not support HTML5 canvas tag.

JavaScript:

<!DOCTYPE html>
<html>
<head>
<title>Usage of HTML canvas createPattern() method (Basic Tutorial Website oldtoolbag.com)</title>/<title>
</<head>
<body>
<p>Image applied:/p>
<img src="haha.gif" id="lamp">
<p>Canvas:/p>
<button onclick="draw('repeat#39;)">Repeat</button> 
<button onclick="draw('repeat-x#39;)">Repeat-x</button> 
<button onclick="draw('repeat-39;)">Repeat-y</button> 
<button onclick="draw('no-repeat#39;)">Not Repeat</button>     
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3>
Your browser does not support HTML5 canvas tag.
</canvas>
<script>
function draw(direction)
{
    var c=document.getElementById("myCanvas");
    2d');
    ctx.clearRect(0,0,c.width,c.height); 
    var img=document.getElementById("lamp")
    var pat=ctx.createPattern(img,direction);
    ctx.rect(0,0,220,128);
    ctx.fillStyle=pat;
    ctx.fill();
}
</script>
</body>
</html>
Test to see ‹/›

Browser Compatibility

IEFirefoxOperaChromeSafari

Internet Explorer 9Firefox, 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, video, or another <canvas> element.
Repeated elements can be used to draw/Fill rectangles, circles, lines, and more.

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

Parameter value

ParameterDescription
imageSpecifies the image, canvas, or video element to be used for the pattern. 
repeatDefault. This mode repeats in both horizontal and vertical directions.
repeat-xThis mode repeats only in the horizontal direction.
repeat-yThis mode repeats only in the vertical direction.
no-repeatThis mode is displayed only once (not repeated).
HTML canvas reference manual