How to use HTML5 Canvas Pattern

This article describes about HTML5 Canvas Pattern.
  • 2340

HTML5 Canvas Pattern

For create pattern in HTML5 use the createPattern() method of the canvas context, then we can set it style using the fillStyle property, and fill it shape using the fill() method. And createPattern() method requires image object and repeat option, these are repeated repeat-x, repeat-y, or no-repeat. The repeat option is defaulted to repeat.



  var patt = context.createPattern(imageObj, repeatOption);

  context.fillStyle = patt;









      body {

        margin: 0px;

        padding: 0px;


      #myCanvas {

        border: 1px solid #9C9898;




        window.onload = function () {

            var canvas = document.getElementById("myCanvas");

            var context = canvas.getContext("2d");


            var imageObj = new Image();

            imageObj.onload = function () {

                var patt = context.createPattern(imageObj, "repeat");

                context.rect(15, 15, canvas.width - 20, canvas.height - 20);

                context.fillStyle = patt;








    <canvas id="myCanvas" width="578" height="200"></canvas>





HTML5 canvas pattern pic 3.jpg

Further Readings

You may also want to read these related articles :

  • HTML5 article

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.