You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现SVG虚线的绘制与流动联动动画?

实现SVG虚线绘制与流动的联动动画

方案1:绘制线条的同时让虚线流动

无需使用遮罩,直接通过控制stroke-dasharray和stroke-dashoffset的动画,让线条绘制与虚线流动同步进行。核心是将虚线的段长、间隔与线条总长度结合,通过动画偏移实现双重效果。

.combined-draw-flow .path {
  stroke: #3835B9;
  stroke-width: 5;
  fill: none;
  stroke-miterlimit: 10;
  /* 虚线设置:10为线段长度,7为间隔,最后加上线条总长度364,实现绘制效果 */
  stroke-dasharray: 10 7 364;
  stroke-dashoffset: 364;
  /* 同步应用绘制与流动动画,linear保证匀速 */
  animation: draw-flow 3s linear forwards;
}

@keyframes draw-flow {
  0% {
    stroke-dashoffset: 364;
  }
  100% {
    /* 偏移量设为 -(10+7),让虚线持续流动,同时线条完全绘制 */
    stroke-dashoffset: -17;
  }
}
<svg class="combined-draw-flow" width="700" height="700">
  <path 
        class="path"
        d="M 280 270 L 470 410 L 410 460 L 450 490"
        ></path>
</svg>

方案2:先完成线条绘制再启动流动动画

通过动画延迟或关键帧分段,先完成线条绘制动画,再触发虚线的无限流动动画。这里用animation-delay让流动动画在绘制完成后启动,同时给绘制动画设置forwards保持最终状态。

.draw-then-flow .path {
  stroke: #3835B9;
  stroke-width: 5;
  fill: none;
  stroke-miterlimit: 10;
  /* 初始设置为线条总长度,实现绘制效果 */
  stroke-dasharray: 364;
  stroke-dashoffset: 364;
  /* 先执行绘制动画并保持最终状态,再启动无限流动动画 */
  animation: draw 1.5s linear forwards, flow 3s linear infinite;
  /* 流动动画延迟1.5s,等绘制完成再启动 */
  animation-delay: 0s, 1.5s;
}

@keyframes draw {
  to {
    stroke-dashoffset: 0;
    /* 绘制完成后,修改dasharray为虚线样式 */
    stroke-dasharray: 10 7;
  }
}

@keyframes flow {
  to {
    stroke-dashoffset: -17; /* 偏移量为虚线段长+间隔的负数,实现循环流动 */
  }
}
<svg class="draw-then-flow" width="700" height="700">
  <path 
        class="path"
        d="M 280 270 L 470 410 L 410 460 L 450 490"
        ></path>
</svg>

关键要点说明

  • 线条总长度364可通过getTotalLength()方法在JS中获取准确值,避免手动计算误差。
  • 虚线流动的偏移量需设置为-(线段长度+间隔),确保动画循环时无卡顿或断层。
  • 方案2中,绘制动画的关键帧最后修改stroke-dasharray,保证绘制完成后切换为虚线样式再启动流动。

内容的提问来源于stack exchange,提问作者hyhy1011

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:55:15