var 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:
imageObject is an image that will be used as a pattern. The source of the image can be:
repeat determines how the imageObject will be repeated across the canvas (much like a CSS background). This argument must be quote delimited and valid values are:
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.
patternimage.onload
) before you attempt to use it to create your pattern.You create a pattern like this:
// create a pattern
var pattern = ctx.createPattern(patternImage,'repeat');
ctx.fillStyle=pattern;
Then Canvas will "invisibly" see your pattern creation like this:
But until you stroke()
or fill()
with the pattern, you will see none of the pattern on the Canvas.
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>