使用画布获取变换后的坐标

发布于 2024-11-09 15:48:17 字数 433 浏览 4 评论 0 原文

如果我在画布上使用像 translate/rotate 这样的转换函数,那么当传递给任何画布函数时,所有点都会被转换。这就像一个魅力,但是否还有一种方法可以简单地获得变换点而不实际绘制?

这在调试时非常有帮助。我现在所能做的就是查看该点的结束位置,但我似乎无法获得计算出的变换坐标。

那么,假设我旋转 90 度,是否有任何函数可以获取一个点(即 (10, 0))并返回变换后的点(即 (0, 10) >)?

我的意思基本上是这样的:

ctx.rotate(90 * Math.PI / 180);
ctx.transformed(10, 0); // would return (0, 10) as an array or something

If I use a transformation function like translate/rotate on a canvas, then all points are transformed when passed to any canvas function. This works like a charm, but is there also a way to simply get the transformed point without actually drawing?

This will be extremely helpful when debugging. All I can do now is looking where the point ends up, but I cannot seem to obtain the calculated transformed coordinates.

So, say I rotate 90 degrees, is there any function that takes a point (i.e. (10, 0)) and gives the transformed point back (i.e. (0, 10))?

I basically mean something like this:

ctx.rotate(90 * Math.PI / 180);
ctx.transformed(10, 0); // would return (0, 10) as an array or something

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨洒年华 2024-11-16 15:48:17

现在可以使用从 DOMMatrix ="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getTransform" rel="noreferrer">CanvasRenderingContext2D.getTransform():

const point = {x: 0, y: 0};
const matrix = ctx.getTransform();
const transformedPoint = {
  x: matrix.a * point.x + matrix.c * point.y + matrix.e,
  y: matrix.b * point.x + matrix.d * point.y + matrix.f,
};

This is possible now, using the DOMMatrix returned from CanvasRenderingContext2D.getTransform():

const point = {x: 0, y: 0};
const matrix = ctx.getTransform();
const transformedPoint = {
  x: matrix.a * point.x + matrix.c * point.y + matrix.e,
  y: matrix.b * point.x + matrix.d * point.y + matrix.f,
};
北座城市 2024-11-16 15:48:17

简短的回答是“不是默认的”。

您需要自己跟踪当前的转换,因为无法获取它(人们已经提交了

Cake.js 这样的库,以及我们很多人,本质上都是按顺序复制转换代码跟踪它,这样我们就可以做这样的事情。一旦你跟踪它,你所需要的就是:

function multiplyPoint(point) {
  return {
    x: point.x * this._m0 + point.y * this._m2 + this._m4,
    y: point.x * this._m1 + point.y * this._m3 + this._m5
  }
}

The short answer is 'not by default.'

You will need to keep track the current transformation yourself because there is no way to get it (people have submitted bugs because this seems so unnecessary).

Libraries like Cake.js, and a lot of us, essentially duplicate the transformation code in order to keep track of it so we can do stuff like this. Once you keep track of it, all you need is:

function multiplyPoint(point) {
  return {
    x: point.x * this._m0 + point.y * this._m2 + this._m4,
    y: point.x * this._m1 + point.y * this._m3 + this._m5
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文