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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…