HTML5 Canvas

HTML5 Canvas: Patterns

HTML5 Canvas: Patterns

Patterns in the form of repeating images can be applied to shapes and outlines of shapes within a Canvas. In this post I shall be exploring the steps to achieve this.

Repeating background pattern

First of all, I am going to apply a repeating pattern image to a square shape:

HTML5 Canvas repeating pattern applied to shape

View demo

The markup

  • First, a variable is created for the image (in this case, I’ve called it img) and I specify the file location of the image I would like to use as the pattern.
  • I then call a function when the image loads, containing another variable (called ptrn) with the context createPattern calling the img variable we created earlier and setting it to repeat.
  • The fill of the shape is created with the context fillStyle and calls the variable ptrn.
  • Lastly, the shape is drawn which I want this pattern applied to – in this case, a 200 x 200 pixel square.
View markup
Javascript portion
function draw() {	
	// Image repeating pattern on background
	var canvas = document.getElementById("patternRepeatBg");
		if (canvas.getContext){
        	var ctx = canvas.getContext("2d"); 
			
		var img = new Image();  
  		img.src = 'images/pattern.png';  
  		img.onload = function(){ 
  			var ptrn = ctx.createPattern(img,'repeat');  
    			ctx.fillStyle = ptrn;  
    			ctx.fillRect(0, 0, 200 ,200);  
  		};
	}
HTML portion
<body onLoad="draw();">
	<canvas id="patternRepeatBg" width="200" height="200"></canvas>
</body>

Repeating pattern applied to shape outline

Patterns can also be applied to the outline of any shape. In my example below, I’ve made the outline quite wide, so the repeating pattern can be seen clearly.

HTML5 Canvas repeating pattern applied to shape outline

View demo

The markup

To apply a repeating pattern to a shape’s outline, we follow exactly the same method as the previous example, but instead of using fillRect to fill in the shape with the pattern, I’ve set the context of lineWidth to 10 to create a 10 pixel wide outline, then used the context of strokeRect to draw just the shape’s outline .

View markup
Javascript portion
function draw() {	
	// Image repeating pattern on outline
	canvas = document.getElementById("patternRepeatOutline");
	if (canvas.getContext){
        	var ctx = canvas.getContext("2d"); 
			
		var img = new Image();  
  		img2.src = 'images/pattern.png';  
  		img2.onload = function(){ 
  			var ptrn = ctx.createPattern(img,'repeat');  
    			ctx.strokeStyle = ptrn;  
			ctx.lineWidth = 10;
    			ctx.strokeRect(5, 5, 190 ,190);  
  		};
	}
HTML portion
<body onLoad="draw();">
	<canvas id="patternRepeatOutline" width="200" height="200"></canvas>
</body>