How to position Path2D SVG element in canvas?

99封情书 提交于 2021-01-01 18:36:30

问题


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

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?


回答1:


Use the transform to move the path

Using 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

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

let p = new Path2D('M10 10 h 80 v 80 h -80 Z');
ctx.transform(1, 0, 0, 1, 100, 100);  
ctx.fill(p);


来源:https://stackoverflow.com/questions/59631446/how-to-position-path2d-svg-element-in-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!