I’m drawing a path2D SVG shape on canvas. The problem is that the moveTo function does not seem to work when using SVG data.
The problem is illustrated in this codepen. https://codepen.io/grasmachien/pen/rNaJeBN
JavaScript
x
7
1
const canvas = document.getElementById('canvas');
2
const ctx = canvas.getContext('2d');
3
4
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
5
p.moveTo(100,100)
6
ctx.fill(p);
7
Is there a way to move the path without moving the canvas?
Advertisement
Answer
Use the transform to move the path
Using CanvasRenderingContext2D.translate
JavaScript
1
7
1
const canvas = document.getElementById('canvas');
2
const ctx = canvas.getContext('2d');
3
4
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
5
ctx.translate(100, 100);
6
ctx.fill(p);
7
or using CanvasRenderingContext2D.setTransform
JavaScript
1
4
1
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
2
ctx.setTransform(1, 0, 0, 1, 100, 100); // Also resets the transform before applying
3
ctx.fill(p);
4
or using CanvasRenderingContext2D.transform
JavaScript
1
4
1
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
2
ctx.transform(1, 0, 0, 1, 100, 100);
3
ctx.fill(p);
4