Javascript 如何在画布中定位Path2D SVG元素?

Javascript 如何在画布中定位Path2D SVG元素?,javascript,html5-canvas,path-2d,Javascript,Html5 Canvas,Path 2d,我正在画布上绘制path2D SVG形状。 问题在于,在使用SVG数据时,moveTo函数似乎不起作用 此代码笔说明了该问题。 有没有一种方法可以在不移动画布的情况下移动路径?使用变换来移动路径 使用 或使用 或使用 const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let p = new Path2D('M10 10 h 80 v 80 h -80 Z'); p.mo

我正在画布上绘制path2D SVG形状。 问题在于,在使用SVG数据时,moveTo函数似乎不起作用

此代码笔说明了该问题。


有没有一种方法可以在不移动画布的情况下移动路径?

使用变换来移动路径

使用

或使用

或使用

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
p.moveTo(100,100)
ctx.fill(p);
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.translate(100, 100);
ctx.fill(p);
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.setTransform(1, 0, 0, 1, 100, 100);  // Also resets the transform before applying
ctx.fill(p);
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.transform(1, 0, 0, 1, 100, 100);  
ctx.fill(p);