CSS 并不简单--实例带你领略实现SVG动画的姿势

3,901 阅读3分钟

接着上一篇svg实现加载动画之后,这篇将带你领略各种SVG动画的实现姿势。

一、animateTransform

  animateTransform是一个SVG元素,主要实现目标元素变换属性的动画,例如平移、旋转等。

  对于animateTransform动画参数的介绍应该没什么必要了,但是在使用animateTransform的时候,有一个特别特别需要注意的点:坐标系。在SVG中图形的变换中心默认为svg元素的左上角,所以这里你需要适当的设置坐标变换的中心。下面来看个例子:

animateTransform星球轨迹动画

    svg(viewBox="0 0 1000 200")
        circle(cx="500" cy="100" r="50" fill="rgb(73,0,204)")
        g(class="track")
            circle(cx="500" cy="100" r="50" fill="none" stroke="rgb(253,183,42)" stroke-width="4" stroke-linecap="round" stroke-dasharray="15.65")
                animateTransform(attributeName="transform" type="rotate" from="360 500 100" to="0 500 100" dur="4s" repeatCount="indefinite")
        path(d="M500 50 C472.4 50 450 72.4 450 100 L550 100 C550 72.4 527.6 50 500 50" fill="rgb(73,0,204)")

  这里我们主要采用animateTransform实现动画效果,需要再次强调的:

  • from中额外的两个值就是用来设置坐标变换中心的;
  • 在svg中后声明的图形会覆盖之前声明的图形,这里我们采用这一特性,实现了一个看似3D的效果。

二、animateMotion

  animateMotion同样也是一个SVG元素,它主要实现:让目标元素在路径上运动。它与前面的区别就是要设置一个目标元素运动的path,来看个栗子:

animateMotion实现的路径动画

    svg(viewBox="0 0 1000 200" class="svg1")
        circle(class="c1" cx="300" cy="100" r="10" fill="rgb(255,210,0)")
        circle(class="c2" cx="400" cy="100" r="10" fill="rgb(255,210,0)")
        circle(class="c3" cx="500" cy="100" r="10" fill="rgb(255,210,0)")
        circle(class="c4" cx="600" cy="100" r="10" fill="rgb(255,210,0)")
        circle(class="c5" cx="700" cy="100" r="10" fill="rgb(255,210,0)")
        circle(class="c" cx="200" cy="50" r="10")
            animateMotion(path="M0 0 L200 100 L400 0 L600 100 L300 25 L0 100 L0 0" dur="6s" repeatCount="indefinite")

  这里我采用了简单的path路径,如果要做复杂的效果,最好还是用AE什么的导出svg的path。手动写太费劲了(不愧是大前端啊)。这个动画效果的碰撞检测写的有点寒碜,我就不放出来。(-_-)

三、animate

  animate当然也是一个SVG元素,主要实现单属性的过渡效果,当然需要实现多个属性的组合动画,你可以声明多个:

animate圆环动画

svg(viewBox="0 0 1000 200")
    circle(class="some" cx="500" cy="100" r="50" stroke="rgb(73,0,204)" stroke-width="4" fill="none")
        animate(attributeName="stroke-dashoffset" values="-313.66;0" dur="2s" repeatCount="indefinite")
        animate(attributeName="stroke-dasharray" values="313.66 313.66;0 313.66" dur="2s" repeatCount="indefinite")

  这个基本没什么要说的。老套路的stroke-dasharray和stroke-dashoffset。

四、总结

  其实我们也可以采用CSS3来实现这里的动画效果。这篇文章讲的基础比较少,当然如果你已经对SVG产生了兴趣,下面的参考资料对你应该有帮助:

参考资料 张鑫旭 理解SVG坐标系统 张鑫旭 SVG动画讲解


  喜欢本文的小伙伴们,欢迎关注我的订阅号超爱敲代码,查看更多内容.