对 SVG 组进行动画处理

Spe*_*rds 5 css animation svg

我目前有以下 SVG:

<svg class="tower owner" height="60" width="60" viewBox="0 0 300 300">
    <g transform="translate(75 75)" opacity="1">
        <ellipse class="border" cx="0" cy="0" fill="#222" rx="65" ry="65" stroke-width="5"></ellipse>
        <g class="rotatable" style="transform: rotate(5.497787143782138rad); transition: transform 2s;">
            <rect fill="#aaa" height="50" stroke-width="7" stroke="#181818" width="40" x="-20" y="-80"></rect>
            <rect fill="#555" height="58" rx="12" ry="10" width="78" x="-39" y="-25"></rect>
            <rect fill="#ffe56d" height="46.4" y="-13.399999999999999" rx="12" ry="12" width="78" x="-39"></rect>
        </g>
    </g>
</svg>
Run Code Online (Sandbox Code Playgroud)

我目前正在制作旋转动画,g.rotatable但如果可能的话我想使用<animateTransform>,但我还没有弄清楚如何使用。

我尝试将它放在组的开头、底部,甚至在它之后,但是没有任何影响。

    <animateTransform attributeName="transform" attributeType="XML" dur="5s" keyTimes="0;0.4;0.75;1" repeatCount="indefinite" type="rotate" values="315deg;90deg;200deg;315deg" calcMode="linear"></animateTransform>
Run Code Online (Sandbox Code Playgroud)

由于我从未真正使用过 SVG 或对其进行动画处理,因此我不确定我哪里出错了。

svg.tower .rotatable {
    animation: tower 5s linear infinite;
}

@keyframes tower {
    0% {
        transform: rotate(315deg);
    }
    40% {
        transform: rotate(90deg);
    }
    75% {
        transform: rotate(200deg);
    }
    100% {
        transform: rotate(315deg);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面是我当前的 CSS 动画。

谁能告诉我哪里出错了,这样我就可以纠正我的错误,或者如果有可能的话,这样我就可以放弃这条行动路线。

Har*_*rry 5

注意:您可能需要重新考虑使用 SMIL 动画而不是 CSS 动画,因为Chrome 从 v45 开始不再支持 SMIL 动画

您的代码中有两个问题,如下所示:

  1. rotateSVG 中的变换仅将度数作为值,不需要deg添加后缀。此外,还可以指定变换原点(第二和第三参数),但这不是强制性的。
  2. style='transform: rotate(...)'元素上有一个.rotatable。CSS 覆盖了animateTransform,所以你看不到任何旋转。避免这种style设置。如果需要初始旋转,您可以使用 SVG 的transform属性。

下面是一个工作演示:

<svg class="tower owner" height="60" width="60" viewBox="0 0 300 300">
  <g transform="translate(75 75)" opacity="1">
    <ellipse class="border" cx="0" cy="0" fill="#222" rx="65" ry="65" stroke-width="5"></ellipse>
    <g class="rotatable" transform="rotate(315)">
      <rect fill="#aaa" height="50" stroke-width="7" stroke="#181818" width="40" x="-20" y="-80"></rect>
      <rect fill="#555" height="58" rx="12" ry="10" width="78" x="-39" y="-25"></rect>
      <rect fill="#ffe56d" height="46.4" y="-13.399999999999999" rx="12" ry="12" width="78" x="-39"></rect>
      <animateTransform attributeName="transform" attributeType="XML" dur="5s" keyTimes="0;0.4;0.75;1" repeatCount="indefinite" type="rotate" values="315;90;200;315" calcMode="linear"></animateTransform>
    </g>
  </g>
</svg>
Run Code Online (Sandbox Code Playgroud)

  • 来自 https://developer.mozilla.org/en-US/docs/Web/SVG/SVG_animation_with_SMIL:_尽管 Chrome 45 弃用了 SMIL,转而支持 CSS 动画和 Web 动画,但 Chrome 开发人员已[暂停](https:// groups.google.com/a/chromium.org/d/msg/blink-dev/5o0yiO440LM/YGEJBsjUAwAJ) 弃用._ (2认同)