How to position Path2D SVG element in canvas?(如何在画布中定位 Path2D SVG 元素?)
问题描述
我正在画布上绘制一个 path2D SVG 形状.问题是 moveTo 函数在使用 SVG 数据时似乎不起作用.
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.
此代码笔说明了该问题.https://codepen.io/grasmachien/pen/rNaJeBN
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?
推荐答案
使用变换移动路径
使用 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);
这篇关于如何在画布中定位 Path2D SVG 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在画布中定位 Path2D SVG 元素?


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01