简体   繁体   English

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

[英]Make a SVG transform matrix rotate around its center

HTML HTML

<rect id="red" style="fill: red;" height="100" width="20"></rect>

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

Now i want to do the same only with a matrix. 现在我只想对矩阵做同样的事情。 I'm using sylvester to multiply the matrixes. 我正在使用西尔维斯特将矩阵相乘。

I made a fiddle to make the question clear :) 我做了一个小提琴以使问题更清楚:)

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

I want the red rect to behave the same as the green rect. 我希望红色矩形的行为与绿色矩形相同。 What am i doing wrong? 我究竟做错了什么?

Fixed!! 固定!! the sequence of the matrix elements was wrong :) 矩阵元素的顺序是错误的:)

$("#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/ http://jsfiddle.net/6DR3D/2/

The problem is the rotate(angle, x, y) call. 问题是rotate(angle, x, y)调用。 This call rotates at the given angle around the point (x,y). 该调用围绕点(x,y)旋转给定角度。 But instead you build your matrix to rotate around layer.position. 但是,您可以构建矩阵来围绕layer.position旋转。

In order to rotate around a given point (x,y), relative to the object, you need to first translate to (-x,-y), then rotate and then translate back to (x,y). 为了相对于对象围绕给定点(x,y)旋转,您需要首先平移为(-x,-y),然后旋转,然后平移回为(x,y)。

So if you had a matrix multiplication function Mul it might look something like this: 因此,如果您有矩阵乘法函数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