简体   繁体   English

如何 canvas 中的 position Path2D SVG 元素?

[英]How to position Path2D SVG element in canvas?

I'm drawing a path2D SVG shape on canvas.我正在 canvas 上绘制 path2D SVG 形状。 The problem is that the moveTo function does not seem to work when using SVG data.问题是使用 SVG 数据时,moveTo function 似乎不起作用。

The problem is illustrated in this codepen.这个代码笔说明了这个问题。 https://codepen.io/grasmachien/pen/rNaJeBN 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);

Is there a way to move the path without moving the canvas?有没有办法在不移动 canvas 的情况下移动路径?

Use the transform to move the path使用变换移动路径

Using CanvasRenderingContext2D.translate使用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);

or using CanvasRenderingContext2D.setTransform或使用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);

or using CanvasRenderingContext2D.transform或使用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);

For simple cases, using the context CTM (Current Transform Matrix) is the way to go.对于简单的情况,使用上下文 CTM(电流变换矩阵)是 go 的方法。

However there are cases where you actually want to transform the path definition itself, for instance if you want to also transform the fill-rule (pattern or gradient), or if you want to compose a single path made of multiple Path2D instances.但是,在某些情况下,您实际上想要转换路径定义本身,例如,如果您还想转换填充规则(图案或渐变),或者如果您想组合由多个Path2D实例组成的单个路径。
In such a case, you can use thePath2D#addPath(<Path2D>, <DOMMatrixInit>) method, to transform your original Path2D instance inside an other one:在这种情况下,您可以使用Path2D#addPath(<Path2D>, <DOMMatrixInit>)方法将原始Path2D实例转换为另一个实例:

 const canvas = document.querySelector("canvas"); const ctx = canvas.getContext("2d"); const p1 = new Path2D("M0,0H45V75Z"); const p2 = new Path2D(); // You can pass a simple object p2.addPath(p1, {e: 60, f: 30}); // translate(60, 30) // Or perform more complex operations through an actual DOMMatrix object const mat = new DOMMatrix(); mat.translateSelf(90, 45); mat.rotateSelf(-30, -70, -80); mat.translateSelf(-90, -45); p2.addPath(p1, mat); // can be filled as a single sub-path ctx.fill(p2);
 <canvas></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM