Make a SVG transform matrix rotate around its center

匆匆过客 提交于 2019-12-11 02:41:20

问题


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

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/

I want the red rect to behave the same as the green rect. What am i doing wrong?


回答1:


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/




回答2:


The problem is the rotate(angle, x, y) call. This call rotates at the given angle around the point (x,y). But instead you build your matrix to rotate around 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).

So if you had a matrix multiplication function Mul it might look something like this:

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


来源:https://stackoverflow.com/questions/13663343/make-a-svg-transform-matrix-rotate-around-its-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!