关于svg中stroke-dashoffset的一个问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    .svgContent {
      border: 2px solid #ddd;
      background: #ddd;
      border-radius: 5px;
      width: 50%;
      margin: auto;
      height: 40px;
      line-height: 40px;
      padding-top: 20px;
    }
    .lineAnimation {
      -webkit-animation: testMove 3s linear infinite;
    }
    @-webkit-keyframes testMove {
      from {
        stroke-dashoffset: 100%
      }
      to {
        stroke-dashoffset: 0
      }
    }
    </style>
</head>
<body>
    <div class="svgContent">
      <svg viewBox="0 0 300 10">
          <line class="lineAnimation" x1="0" y1="0" x2="300" y2="0" 
          stroke="black" stroke-width="10" stroke-dasharray="40,10" stroke-dashoffset="" />
      </svg>
    </div>
</body>
</html>

不是很理解stroke-dashoffset:100% ----> 0这个变化过程
好像是因为100% 和 0%的时候不重合,动画在重复执行的时候,出现了闪动的情况。
问题来源:在使用leaflet-ant-path这个插件的时候发现了这个问题,查看源码发现动画效果就是改变stroke-offset:100% ---> 0
leaflet-ant-path官网地址:https://rubenspgcavalcante.gi...
官网给出的效果图同样也有这个问题。。。

阅读 3.9k
2 个回答

确实是因为0和100%不重合,这是因为虽然这个100%是相对stroke-dasharray的位置,但是100%本身的值却是相对于当前的viewport,所以这里的100%换算成px,并不是300px ...

因此,要达到平滑循环的效果,如果stroke-dashoffset使用百分比,那么stroke-dasharray也要一起使用百分比。同时,无论使用百分比还是具体数值,stoke-dashoffset的起止点要是stroke-dasharray之和的倍数,数值越大,视觉上移动速度越快。

‘stroke-dashoffset’ specifies the distance into the dash pattern to start the dash.
If a <percentage> is used, the value represents a percentage of the current viewport (see Units).
Values can be negative.
https://www.w3.org/TR/SVG11/p...

你理解没错,是100% 和 0%的时候不重合所以出错了,你弄个可以重合的值就好了。 stroke-dasharray="40,10", 所以你设置个 40+10 = 50的倍数,保证from 和to的的样子是一致的就好了

@-webkit-keyframes testMove {

  from {
    stroke-dashoffset: 50; /* 40 + 10的倍数*/
  }
  to {
    stroke-dashoffset: 0
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题