How to Use a Pattern as a Fill or Stroke with the HTML5 Canvas Tag - dummies

How to Use a Pattern as a Fill or Stroke with the HTML5 Canvas Tag

By Andy Harris

Nearly every operation in HTML5’s canvas function implements a fill or stroke style. To get the most out of canvas, you need to understand how they work. The three primary types of styles you can use on fills and strokes are colors, gradients, and patterns.

A pattern is used to define an image to be used as a fill or stroke. You can use any image as a pattern, but it’s generally best to find or create an image designed to be tiled.

There are many sources of tiled patterns available on the web. Once you have an image you want to use as a fill pattern, here’s how to implement it in the canvas tag:

  function draw(){
    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

The results of this code are shown here:


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 are 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. Use the createPattern() method to create 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 axes 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 fillStyle (or strokeStyle) and then perform any fill operation to draw in the pattern.