SMIL 到 CSS 动画:单个元素上的多个动画



现在 SMIL 快要死了,我想将我的简单动画 SVG 转换为使用 CSS 动画,但我不确定如何进行映射。在这个特定的svg中,有两个动画元素。

#embedded {
color: red;
}
<svg id="embedded"  xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
<circle cx="50" cy="50" r="45" stroke="rgba(43,43,43,0.3)" fill="none" stroke-width="10" stroke-linecap="round"/>
<circle cx="50" cy="50" r="45" stroke="currentColor" fill="none" stroke-width="6" stroke-linecap="round">
<animate attributeName="stroke-dashoffset" dur="2s" repeatCount="indefinite" from="0" to="502"/>
<animate attributeName="stroke-dasharray" dur="2s" repeatCount="indefinite" values="150.6 100.4;1 250;150.6 100.4"/>
</circle>
</svg>

虽然我似乎对这些 css 规则开始很好,但我很快就陷入了困境

stroke-dasharray: 150.6 100.4 1 250 150.6 100.4;
animation-duration: 2s;
animation-iteration-count: infinite;
stroke-dashoffset: ?;

完整的映射会是什么样子?可能吗?Sara Soueidan 说,并非所有的动画都可以使用 CSS,而使用 SMIL 可以实现。

下面介绍如何将该 SMIL 动画转换为其等效的 CSS 动画:

  • 您的两个animate标签都有dur="2s",因此CSS动画的持续时间(animation-duration)也将2s。可以使用 long-hand 属性或使用 short-hand 属性指定此值,如下面的代码片段所示。
  • 没有为animate元素指定calcMode属性,因此插值模式为linear。由于插值模式linearanimation-timing-function也会linear
  • repeatCountindefinite,因此animation-iteration-count将被infinite
  • 对于stroke-dashoffset,动画只有一个从(0%)和一个到(100%)的值。因此,在 CSS 动画的关键帧中,我们将stroke-dashoffset指定为0%处的0(from值)和100%处的502(to值)。
  • 对于stroke-dasharray,动画使用而不仅仅是fromto。在这种情况下,有三个分号分隔的值,因此列表中的第一个值在0%关键帧内给出,列表中的第二个值在50%关键帧处给出,最后一个值在100%关键帧选择器中给出。

#embedded, #embedded2 {
color: red;
width: 200px;
height: 200px;
}
#embedded circle#animated {
animation: demo 2s infinite linear;
}
@keyframes demo {
0% {
stroke-dashoffset: 0;
stroke-dasharray: 150.6 100.4;
}
50% {
stroke-dasharray: 1 250;
}
100% {
stroke-dashoffset: 502;
stroke-dasharray: 150.6 100.4;
}
}
<svg id="embedded" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
<circle cx="50" cy="50" r="45" stroke="rgba(43,43,43,0.3)" fill="none" stroke-width="10" stroke-linecap="round" />
<circle cx="50" cy="50" r="45" stroke="currentColor" fill="none" stroke-width="6" stroke-linecap="round" id="animated">
</circle>
</svg>
<svg id="embedded2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid">
<circle cx="50" cy="50" r="45" stroke="rgba(43,43,43,0.3)" fill="none" stroke-width="10" stroke-linecap="round" />
<circle cx="50" cy="50" r="45" stroke="currentColor" fill="none" stroke-width="6" stroke-linecap="round">
<animate attributeName="stroke-dashoffset" dur="2s" repeatCount="indefinite" from="0" to="502" />
<animate attributeName="stroke-dasharray" dur="2s" repeatCount="indefinite" values="150.6 100.4;1 250;150.6 100.4" />
</circle>
</svg>

最新更新