使SVG变换矩阵围绕其中心旋转

时间:2012-12-01 20:18:33

标签: javascript math matrix svg transform

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 +')' ) 

现在我想只用矩阵做同样的事情。我正在使用西尔维斯特来乘以矩阵。

我小心翼翼地提出问题:)

http://jsfiddle.net/xYsHZ/3/

我希望红色矩形的行为与绿色矩形相同。我做错了什么?

2 个答案:

答案 0 :(得分:1)

固定!!矩阵元素的顺序是错误的:)

$("#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);

http://jsfiddle.net/6DR3D/2/

答案 1 :(得分:0)

问题是rotate(angle, x, y)电话。 该调用以点(x,y)周围的给定角度旋转。 但是你建立你的矩阵来围绕layer.position旋转。

为了围绕给定点(x,y)相对于对象旋转,您需要首先转换为(-x,-y),然后旋转然后转换回(x,y)。 / p>

因此,如果你有一个矩阵乘法函数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
相关问题