如何为SVG虚线从一个点到另一个动画?

时间:2019-08-22 17:17:03

标签: html css xml animation svg

我想了解如何像这样制作动画:

PIC1

PIC2

PIC3

我有这个svg代码(x1,x2,y1,y2是动态分配)

<svg id={props.id} class="connect" width="100%" height="100%" viewBox="100%">
   <line lass="path_in" x1={x1} y1={y1} x2={x2} y2={y2} stroke="#5184AF" stroke-width="5" stroke-linecap="round" stroke-dasharray="1, 10"/>
</svg>

我尝试:

svg .path_in {
    stroke-dasharray: 1300;
    animation: dash 4s linear;
    -webkit-animation: dash 4s linear;
  }
  @keyframes dash {
    from {
      stroke-dashoffset: 1300;
    }
    to {
      stroke-dashoffset: 0;
    }
  }
  @-webkit-keyframes dash {
    from {
      stroke-dashoffset: 1300;
    }
    to {
      stroke-dashoffset: 0;
    }
}

1 个答案:

答案 0 :(得分:2)

制作动画的一种方法是使用SMIL动画,如下所示:

svg{border:1px solid}
<svg viewBox="0 0 100 50">
   <line lass="path_in" x1="10" y1="25" x2="10" y2="25" stroke="#5184AF" stroke-width="5" stroke-linecap="round" stroke-dasharray="1, 10">
    <animate 
       attributeName="x2"
       attributeType="XML"
       from="10" to="90"
       dur="4s"
       repeatCount="indefinite"/>
   </line>
</svg>

在此演示中,<animate>元素为x2属性from="10"(与x1相同的值)to="90"设置了动画。动画的持续时间为4秒:dur="4s"

观察:您不需要width="100%",因为如果不声明svg元素的宽度和高度,默认情况下将占用所有可用宽度。

相关问题