我有许多不同大小的 svg 形状,我必须动态地以不同的 Angular 旋转它们。我想使用矩阵将它们集中旋转,我在计算矩阵的 e、f 时遇到了问题。如何计算矩阵(a、b、c、d、e、f)中的 e、f。我有一个 Angular ,但不知道如何计算新位置,所以它看起来在中心旋转。这是我旋转 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>
最佳答案
关于变换和矩阵乘法如何工作的介绍超出了 Stack Overflow 答案的范围。有大量的在线资源。
您还可以阅读 SVG 规范中 SVG 转换的工作原理:
http://www.w3.org/TR/SVG/coords.html
但基本上要围绕特定点 (cx,cy) 旋转 Angular (a),您必须结合(使用矩阵乘法)这三个操作:
- 将中心平移回原点 (-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 ]
When you multiply those three matrices together you get a matrix of the form:
[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 ]
or in SVG form:
matrix( ca, sa, -sa, ca, (-ca * x + sa * y + x), (-sa * x - ca * y + y) )
地点:
ca = cos(angle)
sa = sin(angle)
这是一个演示。绿色矩形使用的是 transform="rotate(a,x,y)"
,红色矩形使用的是我们计算出的等效值。
var matrix = getMatrixForRotation(45, 250, 250);
document.getElementById("myrect").setAttribute("transform", matrix);
function getMatrixForRotation(a, cx, cy)
{
var ca = Math.cos(a * Math.PI / 180);
var sa = Math.sin(a * Math.PI / 180);
var a = ca.toFixed(4);
var b = sa.toFixed(4);
var c = (-sa).toFixed(4);
var d = ca.toFixed(4);
var e = (-ca * cx + sa * cy + cx).toFixed(4);
var f = (-sa * cx - ca * cy + cy).toFixed(4);
return "matrix(" + [a,b,c,d,e,f].join(' ') + ")";
}
<svg width="500" height="500">
<rect x="100" y="150" width="300" height="200" fill="#eee"/>
<rect x="100" y="150" width="300" height="200" fill="none"
stroke="green" stroke-width="10"
transform="rotate(45 250 250)"/>
<rect x="100" y="150" width="300" height="200" fill="none"
stroke="red" stroke-width="4"
id="myrect"/>
</svg>
关于javascript - 使用矩阵围绕中心旋转 Svg 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31446613/