How to Build a Pattern on JavaScript’s Canvas for HTML5 and CSS3 Programming

By Andy Harris

A pattern is used in JavaScript to define an image to be used as a fill or stroke. You can use any image on your HTML5 page as a pattern, but it’s generally best to find or create an image that is designed to be tiled. Many sources of tiled patterns exist on the web as well.

After you’ve got an image you want to use as a fill pattern, here’s how to implement it in the <canvas> tag:


 function draw(){
 //from pattern.html
 var drawing = document.getElementById("drawing");
 var con = drawing.getContext("2d");
 var texture = document.getElementById("texture");
 pFill = con.createPattern(texture, "repeat");
 con.fillStyle = pFill;
 con.font = "40px sans-serif";
 con.fillText("Pattern!", 20, 80);
 con.strokeStyle = pFill;
 con.lineWidth = 5;
 con.strokeRect(10, 10, 180, 100);
 } // end draw

A pattern is simply an image. Building a pattern is relatively straightforward:

  1. Get access to an image.

    You’ll need a JavaScript image object to serve as the basis of your pattern. There’s a number of ways to do this, but the easiest is to create the image somewhere in your HTML, hide it with the display:none style, and use the standard document.getElementById technique to get access to your image.

  2. Create a variable for the pattern.

    Like gradients, pattern fills can be reused, so store the pattern in a variable for later reuse.

  3. Build the pattern.

    The context’s createpattern() method creates a pattern from an image.

  4. Specify the pattern’s repeat parameter.

    The second parameter indicates how the pattern will repeat. The default value is repeat, which repeats the pattern in both the X and Y axis indefinitely. If your pattern is not tiled, you will see a visible seam where the pattern repeats. You can also set the repeat value to repeat-x, repeat-y, and no-repeat.

  5. Apply the pattern variable to the fillStyle or strokeStyle.

    Assign the pattern variable to the context’s and then perform any fill operation to draw in the pattern.