Summary -

In this topic, we described about the Create Pattern with detailed example.

createPattern() method used to create pattern by using a picture on the canvas in HTML5. It returns a pattern object, places the fillStyle property to the pattern object, and then fill the shape using fill().

The createPattern() technique requires an image object and a repeat alternative(that are repeat-x, repeat-y, or no-repeat, repeat.)

Syntax -

createPattern(image, repetition)

This method will use picture to build the pattern. The second argument could be a string with one of the following values: repeat, repeat-x, repeat-y, and no-repeat. If the blank string or null is stipulated, repeat will be applied as a default.

Parameter Description
image Stipulates the image, canvas, or video element of the pattern to utilize
repeat Default. The pattern repeats both horizontally and vertically
repeat-x The pattern repeats only horizontally
repeat-y The pattern repeats only vertically
no-repeat The pattern will be exhibited only once (no repeat)

Example -

The below example describes about how to create pattern using the above method.
          #test {
               margin: 0px auto;
     <script type = "text/javascript">
        function drawShape() {
			// get the canvas element using the DOM 
			var canvas = document.getElementById('mycanvas'); 
			// Make sure we don't execute when canvas isn't supported
			if (canvas.getContext){
				// use getContext to use the canvas for drawing
				var ctx = canvas.getContext('2d');
				// create new image object to use as pattern
				var img = new Image();
				img.src = ‘img/pattern.png';
				img.onload = function() {
					// create pattern
					var ptrn = ctx.createPattern(img,'repeat');
					ctx.fillStyle = ptrn;    
            } else {
				alert('You need Safari or Firefox 1.5+ to see this 
  <body id="test" onload="drawShape();">
     <canvas id="mycanvas" width="400" height="350" style="border:2px 
     solid #00d3d3;"></canvas>

Output -

Browser Support

The following browsers with versions in the table indicates the initial browser version that completely supports the createpattern() method -

Method Chrome Edge Firefox Safari Opera
createpattern() Yes 9.0 and above Yes Yes Yes