Att*_* Ch 6 javascript svg matrix
我有很多不同尺寸的svg形状,我必须动态地用不同角度旋转它们.我想用矩阵中心旋转它们,我在计算矩阵的e,f时遇到了问题.如何计算矩阵(a,b,c,d,e,f)中的e,f.我有一个角度,但不知道计算新的位置,所以看起来它是在中心旋转.这是一个我旋转45度的示例形状,

<rect x="0" y="0" width="50" height="50" style="stroke: #3333cc;fill:none;" transform="matrix(1,0,0,1,100,100)"></rect>
<rect x="0" y="0" width="50" height="50" style="fill: #3333cc" transform="matrix(0.707,-0.707,0.707,0.707,100,100)"></rect>
Run Code Online (Sandbox Code Playgroud)
关于转换和矩阵乘法工作原理的介绍超出了堆栈溢出答案的范围。有很多在线资源。
您可以在SVG规范中了解SVG转换的工作方式:
http://www.w3.org/TR/SVG/coords.html
但是基本上要围绕特定点(cx,cy)按角度(a)旋转,您必须结合(使用矩阵乘法)这三个操作:
[1 0 cx] [cos(a)-sin(a)0] [1 0 -cx] [0 1 cy] [sin(a)cos(a)0] [0 1 -cy] [0 0 1] [0 0 1] [0 0 1]
当您将这三个矩阵相乘时,将得到以下形式的矩阵:
[cos(a)-sin(a)(-cos(a)* x + sin(a)* y + x)] [sin(a)cos(a)(-sin(a)* x-cos(a)* y + y)] [0 0 1]
或SVG形式:
matrix( ca, sa, -sa, ca, (-ca * x + sa * y + x), (-sa * x - ca * y + y) )
Run Code Online (Sandbox Code Playgroud)
哪里:
ca = cos(angle)
sa = sin(angle)
Run Code Online (Sandbox Code Playgroud)
这是一个演示。绿色矩形正在使用transform="rotate(a,x,y)",红色矩形正在使用我们计算的等效项。
[1 0 cx] [cos(a) -sin(a) 0] [1 0 -cx] [0 1 cy] [sin(a) cos(a) 0] [0 1 -cy] [0 0 1 ] [ 0 0 1] [0 0 1 ]
[cos(a) -sin(a) (-cos(a) * x + sin(a) * y + x)] [sin(a) cos(a) (-sin(a) * x - cos(a) * y + y)] [0 0 1 ]