在 svg 中,我们有element.getCTM()
返回 a 的方法SVGMatrix
:
[a c e][b d f][0 0 1]
我想从这个矩阵计算 sx 、 sy 和旋转角度。
在 svg 中,我们有element.getCTM()
返回 a 的方法SVGMatrix
:
[a c e][b d f][0 0 1]
我想从这个矩阵计算 sx 、 sy 和旋转角度。
关于这个主题有很多要阅读和学习的内容。我将给出一个基本的答案,但请注意,如果您尝试制作游戏或动画,这不是这样做的方法。
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 不能单独为您提供完整的角度,但它们一起可以。您想使用 atan tan = sin/cos
,因为您实际上想要使用这种问题atan2
:
RAD2DEG = 180 / Math.PI;
rotation = Math.atan2( ctm.b, ctm.a ) * RAD2DEG;
这是 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 put