用画布获取变换坐标 [英] Get transformed coordinates with canvas

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

问题描述

如果我在画布上使用转换函数,例如 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天全站免登陆