Rotating a SVG path using CSS3 around its own center
我有一组SVG路径,其中一个如下:
1 2 3 | <path id="GOL" class="st0" d="M37.5,430.5l-12.4-12.4v-13.3h-4.2c-7.2,0-13.9,2.5-18.7,7.5c-4.7,4.9-7.3,11.3-7.3,18.3 c0,7,2.6,13.5,7.3,18.3c4.8,5,11.4,7.6,18.6,7.6l4.2,0v-13.7L36.7,430.5z M19.7,435.3l-4.9-4.9l4.9-4.9l4.9,4.9L19.7,435.3z M2.4,430.5c0-8.4,5.6-15.1,13.1-16.9v3.8L2.4,430.5l13.1,13.1v3.8C8,445.6,2.4,438.9,2.4,00.5z"></path> |
我尝试使用以下代码进行旋转动画:
1 2 3 4 5 6 7 8 9 10 11 | .stuck #GOL { fill: red; transform: rotate(90deg); } #GOL { transition-property: all; transition-duration: 2s; } |
问题在于路径绕着不规则的距离中心旋转。我希望它绕自己的中心旋转。我必须使用CSS3(因此不能使用svg自己的
通过使用嵌套转换,可以避免使用
基本思想是将路径的旋转中心转换为SVG的原点(左上),然后进行旋转并将其转换回其原始位置。您可以使用嵌套组来实现。
胎冠形状的中心大约为(22,432)。所以我们可以做:
1 2 3 4 5 | <g transform="translate(22 432)"> // translate everything to the path's original position <g transform="rotate(90deg)"> // rotate (around the origin) <path transform="translate(-22 -432)"/> // shift path to the origin </g> </g> |
读取从内部(路径)到最外部组的转换。
下面的演示:
1 2 3 4 5 6 7 8 9 10 11 | #GOL { fill: red; transform: rotate(90deg); } #GOL { transition-property: all; transition-duration: 2s; } |
1 2 3 4 5 6 7 8 9 10 11 | <svg width="500" height="500"> <g transform="translate(22 432)"> <g id="GOL"> <path class="st0" d="M37.5,430.5l-12.4-12.4v-13.3h-4.2c-7.2,0-13.9,2.5-18.7,7.5c-4.7,4.9-7.3,11.3-7.3,18.3 c0,7,2.6,13.5,7.3,18.3c4.8,5,11.4,7.6,18.6,7.6l4.2,0v-13.7L36.7,430.5z M19.7,435.3l-4.9-4.9l4.9-4.9l4.9,4.9L19.7,435.3z M2.4,430.5c0-8.4,5.6-15.1,13.1-16.9v3.8L2.4,430.5l13.1,13.1v3.8C8,445.6,2.4,438.9,2.4,00.5z" transform="translate(-22 -432)"></path> </g> </g> </svg> |
您是否尝试过在CSS中使用
1 | transform-origin: 50% 50%; |
这将从选择器的中间开始任何转换。