2012-12-01 17 views
2

HTML旋转做一个SVG变换矩阵围绕其中心

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

现在我想只能用一个矩阵来这样做。我正在使用sylvester来增加矩阵。

我做了一个小提琴,使问题清晰:)

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

我想红色矩形的行为一样的绿色矩形。我究竟做错了什么?

回答

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/

0

问题是rotate(angle, x, y)调用。 这个调用围绕点(x,y)以给定的角度旋转。 但是,您可以构建您的矩阵来围绕layer.position旋转。为了在相对于对象的给定点(x,y)周围旋转,需要先转换为(-x,-y),然后旋转,然后再转回(x,y)。

所以,如果你有一个矩阵乘法功能德穆尔它可能是这个样子:

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 
+0

因此,我会基本上具有施加到svg元素3点矩阵。或者mul()将3合并为1? – Baijs

+0

mul将三者合为一体 - 它只是矩阵的乘法 –