The CanvasPattern interface represents an opaque object describing a pattern, based on an image, a canvas, or a video, created by the CanvasRenderingContext2D. createPattern() method. It can be used as a fillStyle or strokeStyle .
fillStyle property of the Canvas 2D API specifies the color, gradient, or pattern to use inside shapes. The default style is #000 (black).
The fillRect() method is used to fill the rectangle using the given color. The default color of the fillRect() method is black. Parameters: This method accepts four parameters as mentioned above and described below: x: It stores the x-coordinate of top-left corner of rectangle.
To set the color of an HTML5 Canvas line, we can use the strokeStyle property of the canvas context, which can be set to a color string such as red, green, or blue, a hex value such as #FF0000 or #555, or an RGB value such as rgb(255, 0, 0).
I'm trying to modify the origin of canvas pattern but can't achieve quite what I want.
I need to draw a line filled with a dotted pattern. Dotted pattern is created via createPattern
(feeding it dynamically created canvas element).
The canvas (essentially a red dot) is created like so:
function getPatternCanvas() {
var dotWidth = 20,
dotDistance = 5,
patternCanvas = document.createElement('canvas'),
patternCtx = patternCanvas.getContext('2d');
patternCanvas.width = patternCanvas.height = dotWidth + dotDistance;
// attempt #1:
// patternCtx.translate(10, 10);
patternCtx.fillStyle = 'red';
patternCtx.beginPath();
patternCtx.arc(dotWidth / 2, dotWidth / 2, dotWidth / 2, 0, Math.PI * 2, false);
patternCtx.closePath();
patternCtx.fill();
return patternCanvas;
}
Then a line is drawn using that pattern (canvas):
var canvasEl = document.getElementById('c');
var ctx = canvasEl.getContext('2d');
var pattern = ctx.createPattern(getPatternCanvas(), 'repeat');
// attempt #2
// ctx.translate(10, 10);
ctx.strokeStyle = pattern;
ctx.lineWidth = 30;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(100, 100);
ctx.stroke();
So we get this:
Now, I'd like to offset the origin of those dots, say, by 10px. Translating pattern canvas doesn't help as then we don't get full dots:
And translating context of canvas itself doesn't help as that offsets the line, not the pattern itself:
Translating context doesn't seem to affect pattern origin.
Is there a way to modify offset of pattern itself?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With