使用画布获取转换后的坐标 [英] Get transformed coordinates with canvas

查看:40
本文介绍了使用画布获取转换后的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

简短的回答是默认情况下不是".

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).

Cake.js 之类的库,以及我们中的很多人,基本上都在复制转换代码为了跟踪它,我们可以做这样的事情.跟踪它后,您只需要:

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
  }
}

这篇关于使用画布获取转换后的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆