SVG矩阵分解 [英] Svg matrix decomposition
问题描述
在svg中,我们有方法element.getCTM()
,它以SVGMatrix
的形式返回:
In svg we have method element.getCTM()
which returns a SVGMatrix
as:
[a c e][b d f][0 0 1]
我想根据此矩阵计算sx,sy和旋转角度.
I want to calculate sx , sy and angle of rotation from this matrix.
推荐答案
关于这个主题,有很多东西可以阅读和学习.我会给出一个基本的答案,但是请注意,如果您要尝试制作游戏或动画,那不是做到这一点的方法.
There is a lot to read and learn on this subject. I'll give a basic answer, but be aware, if you are trying to do a game or animations this is NOT the way to do it.
a == sx
和d == sy
,因此您将按以下方式访问它们:
a == sx
and d == sy
, so you'll access these like this:
var r, ctm, sx, sy, rotation;
r = document.querySelector('rect'); // access the first rect element
ctm = r.getCTM();
sx = ctm.a;
sy = ctm.d;
现在旋转a == cos(angle)
和b == sin(angle)
. Asin和acos不能单独给您提供完整的角度,但是他们可以一起给您提供完整的角度.您想从tan = sin/cos
开始使用atan,对于这种问题,您实际上想使用atan2
:
Now for the rotation a == cos(angle)
and b == sin(angle)
. Asin and acos can't alone give you the complete angle, but together they can. You want to use atan since tan = sin/cos
and for just this kind of problem you actually want to use atan2
:
RAD2DEG = 180 / Math.PI;
rotation = Math.atan2( ctm.b, ctm.a ) * RAD2DEG;
如果您研究反三角函数和
If you study the inverse trigonometric functions and the unit circle you'll understand why this works.
这是W3C在SVG转换方面不可或缺的资源: http://www.w3. org/TR/SVG/coords.html .向下滚动一点,您可以阅读有关我上面提到的内容的更多信息.
Here is W3C's indespensible resource on SVG transformations: http://www.w3.org/TR/SVG/coords.html. Scroll down a bit and you can read a lot more about what I've mentioned above.
更新,示例用法,如何以编程方式制作动画.将转换单独保存,并在更新这些转换时,覆盖/更新SVG元素转换.
UPDATE, example usage how to programmatically do animations. Keep the transformations stored separately and when these are updated, overwrite/update the SVG element transform.
var SVG, domElement, ...
// setup
SVG = document.querySelector( 'svg' );
domElement = SVG.querySelector( 'rect' );
transform = SVG.createSVGTransform();
matrix = SVG.createSVGMatrix();
position = SVG.createSVGPoint();
rotation = 0;
scale = 1;
// do every update, continuous use
matrix.a = scale;
matrix.d = scale;
matrix.e = position.x;
matrix.f = position.y;
transform.setMatrix( matrix.rotate( rotation ) );
domElement.transform.baseVal.initialize( transform ); // clear then put
这篇关于SVG矩阵分解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!