Falcon80 Logo
Repetitive patterns on a canvas

In addition to filling an area with specific colours or colour gradients, you can also fill it with an image to create patterns. You can use the createPattern() method to do this.

To apply a pattern to an area, you should first create an image object.

The createPattern() method takes in two parameters viz., an image object and one of the four options: repeat, repeat-x, repeat-y and no-repeat. The default is 'repeat'. The method returns an object that can be assigned to the fillstyle attribute.

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");

Create a new image object
var pattern = new Image();

// polkaDots.png is an image with a single polka dot
pattern.src= "../../Images/Attributes/polkaDots.png";

// Define the pattern
var fillColor = ctx.createPattern(pattern,'repeat');

// Assign the pattern to fillStyle
ctx.fillStyle= fillColor;

ctx.fillRect(50,20,600,300);

}
}
  </script>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>
 
Try Code