簡體   English   中英

如何 canvas 中的 position Path2D SVG 元素?

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

我正在 canvas 上繪制 path2D SVG 形狀。 問題是使用 SVG 數據時,moveTo function 似乎不起作用。

這個代碼筆說明了這個問題。 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);

有沒有辦法在不移動 canvas 的情況下移動路徑?

使用變換移動路徑

使用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);

或使用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);

或使用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);

對於簡單的情況,使用上下文 CTM(電流變換矩陣)是 go 的方法。

但是,在某些情況下,您實際上想要轉換路徑定義本身,例如,如果您還想轉換填充規則(圖案或漸變),或者如果您想組合由多個Path2D實例組成的單個路徑。
在這種情況下,您可以使用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