SVG动画只需添加一个类

时间:2016-04-01 07:36:58

标签: javascript html css svg css-animations

我使用SMIL动画创建了一个svg加载器动画。我只是添加一个类名loader来显示元素中的svg。

Fiddle点击容器查看加载程序

.loader{
    position: relative;
}

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

/* blocker */
.loader::after {
    /* other properties */
}

但现在,我意识到SMIL is deprecated in chrome。所以,我决定使用CSS处理动画。但是如果我使用css处理动画,那么我将无法像上面那样管理代码,只需添加一个类。

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

无论如何,我可以通过在使用CSS动画时添加一个类来管理动画吗?

有些观点:

  • 我不想添加任何新元素。
  • 我将使用JavaScript只是为了添加一个类而不是别的。
  • 我不想生成一个gif(一个光栅图像)。

我有SMIL和CSS动画的小提琴:

我仅限于添加一个类来管理动画,因为它保持了我的代码组织,我觉得也可以使用css动画。

3 个答案:

答案 0 :(得分:6)

您可以在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

答案 1 :(得分:1)

2016年弃用通知很快reversed,因为许多SMIL功能仍然别无选择。编写4年后,它仍不被弃用。

答案 2 :(得分:0)

您可以继续使用SMIL,只需在页面中添加填充即可。这很简单(只需将其添加到页面中),并且可以在所有浏览器上完美运行。我建议你先从Fakesmile开始(https://leunen.me/fakesmile/index.html)。如果您需要更高级的功能和硬件加速功能,请尝试使用Google polyfill(https://github.com/ericwilligers/svg-animation)。

阅读本文以获得更广泛的解释,polyfill列表以及可用于为SVG制作动画的库的评论:
https://medium.com/@fmuaddib/the-following-are-the-possible-ways-to-create-professional-animations-in-svg-9d4caca5f4ec