【发布时间】:2012-01-31 15:33:54
【问题描述】:
在 svg 中,我们有方法 element.getCTM(),它返回 SVGMatrix:
[a c e][b d f][0 0 1]
我想根据这个矩阵计算 sx 、 sy 和旋转角度。
【问题讨论】:
-
帮我解决这个问题。
标签: matrix svg rotation angle decomposition
在 svg 中,我们有方法 element.getCTM(),它返回 SVGMatrix:
[a c e][b d f][0 0 1]
我想根据这个矩阵计算 sx 、 sy 和旋转角度。
【问题讨论】:
标签: matrix svg rotation angle decomposition
关于这个主题有很多要阅读和学习的地方。我将给出一个基本的答案,但请注意,如果您尝试制作游戏或动画,这不是这样做的方式。
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 开始,您就想使用atan,而对于这种问题,您实际上想使用atan2:
RAD2DEG = 180 / Math.PI;
rotation = Math.atan2( ctm.b, ctm.a ) * RAD2DEG;
如果您研究过inverse trigonometric functions 和unit circle,您就会明白为什么会这样。
这是 W3C 关于 SVG 转换的不可或缺的资源:@987654323@。向下滚动一点,您可以阅读更多关于我上面提到的内容。
更新,示例用法如何以编程方式制作动画。将转换单独存储,并在更新这些转换时覆盖/更新 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 put
【讨论】:
animateTransform、animateMotion 和其他动画元素时,您不应该以编程方式控制它们。如果你想以编程方式控制动画,你想直接使用元素变换。我用一个例子更新了我上面的答案。