VixinG VixinG - 5 months ago 15
jQuery Question

Creating HTML5 canvas patterns and filling stuff with them

I'm having diffulties with

.createPattern(image,"repeat")
. 1. Can I fill a square with my own pattern created by
.toDataURL()
and
.createPattern()
?

2. Can I fill a square with pattern, which is the current canvas?

my jsFiddle

HTML



<canvas id="canvas" width="320" height="240" style="border: solid darkblue 1px;background-color: aliceblue"></canvas>


JavaScript



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

context.strokeRect(0.5, 0.5, 10, 10);
context.arc(5.5, 5.5, 3, 0, Math.PI);
context.rect(3, 3, 1, 1);
context.rect(7, 3, 1, 1);
context.stroke();

var img = new Image();
img.src = canvas.toDataURL();
context.drawImage(img, 10, 10); // works

context.beginPath();
var pattern = context.createPattern(img, "repeat"); // doesn't work
context.fillStyle = pattern;
context.fillRect(20, 20, 100, 100);
context.fill();

context.beginPath();
var pattern2 = context.createPattern(canvas, "repeat"); // doesn't work
context.fillStyle = pattern2;
context.fillRect(120, 20, 100, 100);
context.fill();`

K3N K3N
Answer

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.

Modified fiddle

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

// create the off-screen canvas
var 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();