createPattern (creates a path styling object)

suggest change
let pattern = createPattern(imageObject,repeat);

Creates a reusable pattern (object).

The object can be assigned to any strokeStyle and/or fillStyle.

Then stroke() or fill() will paint the Path with the pattern of the object.


The pattern object is an object that you can use (and reuse!) to make your path strokes and fills become patterned.

Side Note: The pattern object is not internal to the Canvas element nor it’s Context. It is a separate and reusable JavaScript object that you can assign to any Path you desire. You can even use this object to apply pattern to a Path on a different Canvas element(!)

Important hint about Canvas patterns!

When you create a pattern object, the entire canvas is “invisibly” filled with that pattern (subject to the repeat argument).

When you stroke() or fill() a path, the invisible pattern is revealed, but only revealed over that path being stroked or filled.

  1. Start with an image that you want to use as a pattern. Important(!): Be sure your image has fully loaded (using patternimage.onload) before you attempt to use it to create your pattern.
  2. You create a pattern like this:
    // create a pattern
    var pattern = ctx.createPattern(patternImage,'repeat');
  3. Then Canvas will “invisibly” see your pattern creation like this:
  4. But until you stroke() or fill() with the pattern, you will see none of the pattern on the Canvas.
  5. Finally, if you stroke or fill a path using the pattern, the “invisible” pattern becomes visible on the Canvas … but only where the path is drawn.
<!doctype html>
    body{ background-color:white; }
    #canvas{border:1px solid red; }

    // canvas related variables
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    // fill using a pattern
    var patternImage=new Image();
    // IMPORTANT! 
    // Always use .onload to be sure the image has
    //     fully loaded before using it in .createPattern
        // create a pattern object
        var pattern = ctx.createPattern(patternImage,'repeat');
        // set the fillstyle to that pattern
        // fill a rectangle with the pattern
        // demo only, stroke the rect for clarity

}); // end window.onload
    <canvas id="canvas" width=325 height=250></canvas>

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents