[英]Make a SVG transform matrix rotate around its center
HTML
<rect id="red" style="fill: red;" height="100" width="20"></rect>
JS
var layer =
{
sizeReal : { "width": 20, "height": 100 }
, sizeScaled : { "width": 10, "height": 50 }
, position : { "x": 200, "y": 200 }
, scale : 0.5
, rotation : 0
, matrix : [ 1, 0, 0, 1, 0, 0 ]
};
// Not sure if its the cleanest way but it works it rotates itself arounds its center.
//
$("#red")[0].setAttribute( 'transform', 'translate(' + layer.position.x + ',' + layer.position.y +') rotate(' + layer.rotation +',' + ( layer.sizeScaled.width / 2 ) + ',' + ( layer.sizeScaled.height / 2 ) + ') scale(' + layer.scale + ',' + layer.scale +')' )
现在我只想对矩阵做同样的事情。 我正在使用西尔维斯特将矩阵相乘。
我做了一个小提琴以使问题更清楚:)
我希望红色矩形的行为与绿色矩形相同。 我究竟做错了什么?
固定!! 矩阵元素的顺序是错误的:)
$("#red")[0].setAttribute( 'transform', 'matrix(' + layer.matrix[ 0 ][ 0 ] + ',' + layer.matrix[ 1 ][ 0 ] + ',' + layer.matrix[ 0 ][ 1 ] + ',' + layer.matrix[ 1 ][ 1 ] + ',' + layer.matrix[ 0 ][ 2 ] + ',' + layer.matrix[ 1 ][ 2 ] + ')' );
},50);
问题是rotate(angle, x, y)
调用。 该调用围绕点(x,y)旋转给定角度。 但是,您可以构建矩阵来围绕layer.position旋转。
为了相对于对象围绕给定点(x,y)旋转,您需要首先平移为(-x,-y),然后旋转,然后平移回为(x,y)。
因此,如果您有矩阵乘法函数Mul,它可能看起来像这样:
var m1 = GetMatrix(0, 0, {"x":-layer.sizeScaled.width/2, "y":-layer.sizeScaled.height/2});
var m2 = GetMatrix(layer.rotation, layer.scale, layer.position);
var m3 = GetMatrix(0, 0, {"x":layer.sizeScaled.width/2, "y":layer.sizeScaled.height/2});
var m = Mul(Mul(m3,m2), m1); //i.e. apply the matricdes in order m1, then m2, then m3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.