Mat*_*ias 5 javascript html5-canvas path-2d
我正在画布上绘制一个 path2D SVG 形状。问题是使用 SVG 数据时 moveTo 函数似乎不起作用。
此 codepen 中说明了该问题。 https://codepen.io/grasmachien/pen/rNaJeBN
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);
Run Code Online (Sandbox Code Playgroud)
有没有办法在不移动画布的情况下移动路径?
使用变换来移动路径
使用CanvasRenderingContext2D.translate
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);
Run Code Online (Sandbox Code Playgroud)
或使用CanvasRenderingContext2D.setTransform
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);
Run Code Online (Sandbox Code Playgroud)
或使用CanvasRenderingContext2D.transform
let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.transform(1, 0, 0, 1, 100, 100);
ctx.fill(p);
Run Code Online (Sandbox Code Playgroud)