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.

Arguments:

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');
    ctx.fillStyle=pattern;
  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>
<html>
<head>
<style>
    body{ background-color:white; }
    #canvas{border:1px solid red; }
</style>
<script>
window.onload=(function(){

    // 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
    patternImage.onload=function(){
        // create a pattern object
        var pattern = ctx.createPattern(patternImage,'repeat');
        // set the fillstyle to that pattern
        ctx.fillStyle=pattern;
        // fill a rectangle with the pattern
        ctx.fillRect(50,50,150,100);
        // demo only, stroke the rect for clarity
        ctx.strokeRect(50,50,150,100);
    }
    patternImage.src='http://i.stack.imgur.com/K9EZl.png';

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

Feedback about page:

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



Table Of Contents