我刚刚使用在线服务为自己生成了一个基于 SVG 的加载指示器,但是每次加载使用它的页面时,我都会收到来自 Chrome 的警告,通知我 SMIL 动画正在被弃用,这相当令人讨厌。为了摆脱它,我决定考虑<animate>
用 Web Animations 替换标签。以下是原始 SVG:
<svg width='200px' height='200px' xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" class="uil-ring-alt">
<circle cx="50" cy="50" r="40" stroke="white" fill="none" stroke-width="10" stroke-linecap="round"/>
<circle cx="50" cy="50" r="40" stroke="#808080" 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>
这就是我最终得到的结果:
<svg width='200px' height='200px' xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" xmlns:xlink="http://www.w3.org/1999/xlink">
<circle cx="50" cy="50" r="40" stroke="white" fill="none" stroke-width="10" stroke-linecap="round"/>
<circle cx="50" cy="50" r="40" stroke="#808080" fill="none" stroke-width="6" stroke-linecap="round" id="line"/>
<script type="text/javascript" xlink:href="https://cdn.rawgit.com/web-animations/web-animations-js/45d8e40300e82ff02ccfbbc78c89500de0f5616f/web-animations.min.js"></script>
<script type="text/javascript"><![CDATA[
var line = document.getElementById("line");
line.animate(
[
{strokeDashoffset:0},
{strokeDashoffset:502}
],
{ duration: 2000, iterations: Infinity }
);
line.animate(
[
{strokeDasharray:"150.6 100.4"},
{strokeDasharray:"1 250"},
{strokeDasharray:"150.6 100.4"}
],
{ duration: 2000, iterations: Infinity }
);
]]></script>
</svg>
background-image
我正要为我设法让它工作而感到非常兴奋,然后当我注意到完全相同的 SVG在 CSS 中用作 a 时,我的笑容僵住了(下面的演示;注意我在这里使用数据 URI 内联了 SVG,但是当使用常规 URL 加载 SVG 时也会发生同样的情况)。
body:before {
content: '';
display: block;
width: 200px;
height: 200px;
background: url('data:image/svg+xml;utf8,<svg width="200px" height="200px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" xmlns:xlink="http://www.w3.org/1999/xlink"><circle cx="50" cy="50" r="40" stroke="white" fill="none" stroke-width="10" stroke-linecap="round"/><circle cx="50" cy="50" r="40" stroke="#808080" fill="none" stroke-width="6" stroke-linecap="round" id="line"/><script type="text/javascript" xlink:href="https://cdn.rawgit.com/web-animations/web-animations-js/45d8e40300e82ff02ccfbbc78c89500de0f5616f/web-animations.min.js"></script><script type="text/javascript"><![CDATA[var line = document.getElementById("line");line.animate([{strokeDashoffset:0},{strokeDashoffset:502}],{ duration: 2000, iterations: Infinity });line.animate([{strokeDasharray:"150.6 100.4"},{strokeDasharray:"1 250"},{strokeDasharray:"150.6 100.4"}],{ duration: 2000, iterations: Infinity });]]></script></svg>') no-repeat center center;
background-size: contain;
}
我应该忽略警告并继续使用 SMIL,还是有办法让 Web 动画在 SVG 中工作?