围绕自己的中心使用CSS3旋转SVG路径

时间:2016-12-19 14:52:45

标签: html css css3 svg css-animations

我有一组SVG路径,其中一个如下:

<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>

我尝试使用以下代码制作旋转动画:

.stuck #GOL
{
  fill: red;
  transform: rotate(90deg);
}

#GOL
{
  transition-property: all;
  transition-duration: 2s;
}

问题是路径围绕不规则的距离中心旋转。我希望它围绕自己的中心旋转。我必须使用CSS3(所以我不能使用svg自己的rotate()函数)。

2 个答案:

答案 0 :(得分:1)

您是否尝试在CSS中使用transform-origin

transform-origin: 50% 50%;

这将从选择器的中间开始任何变换。

答案 1 :(得分:1)

您可以使用嵌套转换来避免使用transform-origin及其相关的浏览器问题。

基本思想是将路径的旋转中心转换为SVG的原点(左上角)进行旋转并将其转换回原始位置。您可以使用嵌套组来实现此目的。

你的皇冠形状的中心是大约(22,432)。所以我们可以这样做:

<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>

从内部(路径)读取转换到最外面的组。

演示如下:

#GOL
{
  fill: red;
  transform: rotate(90deg);
}

#GOL
{
  transition-property: all;
  transition-duration: 2s;
}
<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>

相关问题