在svg中,我们有element.getCTM()方法,它将SVGMatrix返回为:
[a c e][b d f][0 0 1] 我想从这个矩阵中计算sx,sy和旋转角。
发布于 2012-01-02 22:09:47
在这个主题上有很多值得阅读和学习的东西。我会给出一个基本的答案,但请注意,如果你正在尝试做一个游戏或动画,这不是做它的方法。
a == sx和d == sy,所以您将像这样访问它们:
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之后使用atan2,而对于此类问题,您实际上希望使用atan
RAD2DEG = 180 / Math.PI;
rotation = Math.atan2( ctm.b, ctm.a ) * RAD2DEG;如果你研究了inverse trigonometric functions和unit circle,你就会明白为什么会这样。
下面是W3C关于SVG转换的不可缺少的资源:http://www.w3.org/TR/SVG/coords.html。向下滚动一点,你可以读到更多关于我上面提到的内容。
更新,示例用法如何以编程方式制作动画。将转换单独存储,当这些转换更新时,覆盖/更新SVG元素转换。
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 puthttps://stackoverflow.com/questions/8697966
复制相似问题