簡體   English   中英

使SVG變換矩陣繞其中心旋轉

[英]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 +')' ) 

現在我只想對矩陣做同樣的事情。 我正在使用西爾維斯特將矩陣相乘。

我做了一個小提琴以使問題更清楚:)

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

我希望紅色矩形的行為與綠色矩形相同。 我究竟做錯了什么?

固定!! 矩陣元素的順序是錯誤的:)

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

問題是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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM