只需添加一个类即可实现SVG动画

SVG animation by just adding a class

本文关键字:可实现 SVG 动画 一个 添加      更新时间:2023-11-16

我使用SMIL动画创建了一个svg加载程序动画。我只添加了一个类名,即loader,就可以在元素中显示svg。

Fiddle点击容器查看加载器

.loader{
    position: relative;
}
/* image */
.loader::before {
    background-image: url('loader.svg');
    /* other properties */
} 
/* blocker */
.loader::after {
    /* other properties */
}

但现在,我意识到SMIL在chrome中已被弃用。因此,我决定使用CSS处理动画。但是,如果我使用css处理动画,那么我将无法像上面所做的那样管理代码,即仅通过添加一个类。

如果我使用css动画,我需要在容器中添加一个新元素,然后使用内联svg概念IMO.

不管怎样,我可以通过在使用css动画时添加一个类来管理动画吗?

一些要点:

  • 我不想添加任何新元素
  • 我将使用JavaScript只是为了添加一个类,而不做其他任何事情
  • 我不想生成gif(光栅图像

我有SMIL和CSS动画的技巧:

  • 使用SMIL动画的SVG
  • 使用CSS动画的SVG

我只限于添加一个类来管理动画,因为它使我的代码保持有序,而且我觉得用css动画也可以做到这一点。

您可以在loader.svg:中设置css动画

<svg width="100" height="100" xmlns="http://www.w3.org/2000/svg" version="1.1">
  <style>
    rect{
      animation:fill 1s linear infinite;
    }
    @keyframes fill{
      0%{
        fill:#f05223;
      }
      100%{
        fill:white;
      }
    }
    rect:nth-child(2){
      animation-delay:.25s;
    }
    rect:nth-child(3){
      animation-delay:.50s;
    }
    rect:nth-child(4){
      animation-delay:.75s;
    }
  </style>
    <rect width="50" height="50" stroke="white" fill="white"></rect>
    <rect x="50" width="50" height="50" stroke="white" fill="white"></rect>
    <rect x="50" y="50" width="50" height="50" stroke="white" fill="white"></rect>
    <rect width="50" x="0" y="50" height="50" stroke="white" fill="white"></rect>
</svg>

https://plnkr.co/edit/tcbdwaSNgadrKYQr5iex?p=preview

2016年,由于SMIL的许多功能仍然别无选择,弃用通知很快被撤销。即使在4年后写这篇文章时,它也没有被弃用。

您可以继续使用SMIL,只需要在页面中添加一个polyfill即可。它很简单(只需将其添加到页面中),在所有浏览器上都能完美工作。我建议你从Fakesmile(https://leunen.me/fakesmile/index.html)。如果你需要更先进的硬件加速功能,可以试试谷歌polyfill(https://github.com/ericwilligers/svg-animation)。

阅读本文以获得更广泛的解释、polyfill列表以及可用于动画化SVG的库的综述:
https://medium.com/@fmuaddib/the-以下是创建专业动画的可能途径-svg-9d4caca5f4ec