【CSS】SVG(十一)——动画(2)

675 阅读2分钟

这是我参与11月更文挑战的第20天,活动详情查看:2021最后一次更文挑战


SVG(十一)——动画(2)

接上文

(10)动画

<animateMotion>
  • <animateMotion>可以让SVG图像沿着设置的路径进行运动

  • 代码示例

    <circle  cx="0" cy="0" r="25">
        <animateMotion path="M 100 100, Q 150 0 200 100, T 300 100" dur="3s"/>
    </circle>
    

    svg-animate4

    使用path属性来指定当前动画的运动路径

    • path属性的规则同<path>标签的d属性规则
  • 除了使用path属性值,我们还可以来指定一条外部路径

    • 然后使用<mpath>标签来链接到这条指定的路径,从而让SVG图形沿着这条路径进行运动
  • <mpath>标签需要嵌套在<animateMotion>标签内部

    • 通过xlink:href来链接到另一条路径

      <path id="path" d="M 100 100, Q 150 0 200 100, T 300 100" />
      <circle cx="0" cy="0" r="50">
          <animateMotion dur="3s">
              <mpath xlink:href="#path"></mpath>
          </animateMotion>
      </circle>
      
      

      效果同上

      svg-animate4


  • 额外的,xlink:href属性也适用于SVG的其它动画标签,如

    <set xlink:href="#set"></set>
    
    <animate xlink:href="animate"></animate>
    
    <animateTransform xlink:href="transform"></animateTransform>
    
    

  • 对于上述情况,我们设置的圆心坐标(cx,cy)均为0

    • 如果额外设置了圆心的坐标,则其运动路径会稍有变化

    • 其运动路径会在原路径的基础发生偏移,偏移量为设置的cxcy

      如这里设置圆心在Y轴上的坐标为100,则其运动路径会在原来的基础上向下移动100

    <circle cx="0" cy="100" r="25">
        <animateMotion path="M 100 100, Q 150 0 200 100, T 300 100" dur="3s" repeatCount="indefinite" />
    </circle>
    
    

    svg-animate5

    同样的,对于cx的设置同样也会出现类似的效果

    • 其偏移为X轴方向上的偏移

    所以使用SVG的动画标签<animateMotion>的形状其起点需要从原点开始,但路径的位置可以是任意地点

    而如果改变了起点的位置,则其运动路径也会发生相应的偏移,偏移值为起点的偏移值

  • 接下来,我们设置一个箭头形状,给它加上路径动画

    <path d="M 0 0,l 20 0,l -10 -15,l 10 15,l -10 15,l 10 -15,z">
        <animateMotion path="M 100 100, Q 150 0 200 100, T 300 100" dur="3s"/>
    </path>
    
    

    svg-animate6

    可以看到,箭头形状虽然可以沿着路径进行运动,但其方向却始终未变,

    因此,我们可以使用rotate属性来指定当前形状是否随路径方向变化而变化

    • 设置auto表示SVG图形的方向沿路径切线方向
    <path d="M 0 0,l 20 0,l -10 -15,l 10 15,l -10 15,l 10 -15,z">
        <animateMotion path="M 100 100, Q 150 0 200 100, T 300 100" dur="3s" rotate="auto"/>
    </path>
    
    

    svg-animate7

    这样箭头方向就是路径的方向了

    这个属性同motion-path中的offset-rotate属性的作用