SVG直线动画CSS

4
我正在尝试在网站中使用SVG路径进行动画制作,希望实现以下效果(如下图所示)。我看到了https://css-tricks.com/svg-line-animation-works/这篇文章,并想尝试一下。但我不确定如何创建路径和动画。请帮助我!谢谢。

enter image description here

2个回答

5

您可以使用SVG代码进行动画制作。您可以在SVG路径上使用CSS动画。

.st0{
fill:none;
stroke:#000000;
stroke-miterlimit:10;
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
-webkit-animation: draw1 4s linear forwards;
animation: draw1 4s linear forwards;
}
.st1{
fill:none;
stroke:#000000;
stroke-miterlimit:10;
stroke-dasharray: 200;
stroke-dashoffset: 200;
-webkit-animation: draw2 3s linear 2s forwards;
animation: draw2 3s linear 2s forwards;
}
  
@-webkit-keyframes draw1{
  to {stroke-dashoffset: 0;}
}
@keyframes draw1{
  to {stroke-dashoffset: 0;}
}
@-webkit-keyframes draw2{
  to {stroke-dashoffset: 0;}
}
@keyframes draw2{
  to {stroke-dashoffset: 0;}
}
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  viewBox="0 0 614 53" style="enable-background:new 0 0 614 53;" xml:space="preserve">
<polyline class="st0" points="0.5,53 0.5,20.7 613.5,20.7 613.5,53 "/>
<line class="st1" x1="307" y1="53" x2="307" y2="0"/>
</svg>


不包括您的答案中的相关部分。 - ccprog
不包括相关部分是什么意思?提问者认为这很有帮助。 - Ganesh Yadav
你的回答只有在查看 fiddle 时才有意义。为了将来的读者着想,应当在此处提供可理解的答案,而不是链接到外部资源。在您的代码示例中包含 CSS 并不需要太多的努力。 - ccprog
@ccprog,现在好一些了吗? - Ganesh Yadav

2

SVG解决方案

动画使用属性<stroke-dashoffset>,该属性表示线条开始的缩进量。在<stroke-dashoffset>的最大值处,可见线条长度为零。
<stroke-dashoffset ="0">时,线条长度最大。

为避免动画中出现不可预测的效果,需要准确计算线条长度。

在此示例中,<line>的长度为53px,<polyline>的长度为680px。

<style>
.st0{fill:none;stroke:#000000;stroke-miterlimit:10; stroke-dasharray: 680; stroke-dashoffset: 680;} 
.st1{fill:none;stroke:#000000;stroke-miterlimit:10; stroke-dasharray: 53; stroke-dashoffset: 53;}  
 </style>
<svg version="1.1"  viewBox="0 0 614 53" >
 <polyline class="st0" points="0.5,53 0.5,20.7 613.5,20.7 613.5,53 " >
  <animate
    attributeName="stroke-dashoffset"
    from="680"
    to="0"
    dur="2s"
    fill="freeze" />
 </polyline>
<line class="st1" x1="307" y1="53" x2="307" y2="0">
    <animate
      attributeName="stroke-dashoffset"
      from="53"
      to="0"
      dur="2s"
      fill="freeze" />
</line>
 
</svg>


@lel 添加了第二种解决方案是SVG。在您的示例中仅使用CSS不总是可能解决动画任务。 - Alexandr_TT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接