Skip to content Skip to sidebar Skip to footer

Creating Html5 Canvas Patterns And Filling Stuff With Them

I'm having difficulties with .createPattern(image,'repeat'). Can I fill a square with my own pattern created by .toDataURL() and .createPattern()? Can I fill a square with a patte

Solution 1:

You will need to create a separate canvas for the pattern as you cannot self-reference the canvas for use with patterns.

The reason is that when you reference the original canvas you are trying to draw to, the pattern will have the same size and will only draw one instance as there is no room for more than that.

So to make it work you need to define a pattern of a smaller size, hence we need a separate canvas or image and pass that in as a source for the pattern.

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

// create the off-screen canvasvar canvasPattern = document.createElement("canvas");
canvasPattern.width = 10;
canvasPattern.height = 10;
var contextPattern = canvasPattern.getContext("2d");

// draw pattern to off-screen context
contextPattern.beginPath();
contextPattern.strokeRect(0.5, 0.5, 10, 10);
contextPattern.arc(5.5, 5.5, 3, 0, Math.PI);
contextPattern.rect(3, 3, 1, 1);
contextPattern.rect(7, 3, 1, 1);
contextPattern.stroke();

// now pattern will work with canvas element    var pattern = context.createPattern(canvasPattern,"repeat");
context.fillStyle = pattern;
context.fillRect(20, 20, 100, 100);
context.fill();
<canvasid="canvas"width="320"height="240"style="border: solid darkblue 1px;background-color: aliceblue"></canvas>

Post a Comment for "Creating Html5 Canvas Patterns And Filling Stuff With Them"