Get transformed coordinates with canvas

好久不见. 提交于 2019-12-19 09:07:50

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/6098876/get-transformed-coordinates-with-canvas

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