stroke-dashoffset 虚线偏移

详细介绍SVG的stroke-dashoffset虚线偏移属性,学习如何控制虚线的起始位置和创建流动动画效果。通过实例掌握虚线偏移的应用技巧。 stroke-dashoffset属性用于设置虚线模式的起始偏移量,常用于创建虚线动画效果。

基本语法

<element stroke-dashoffset="偏移值"/>

偏移值表示虚线模式从起点偏移的距离,正值向后偏移,负值向前偏移。

偏移效果

offset: 0 offset: 5 offset: 10 offset: 15
<line x1="30" y1="30" x2="270" y2="30" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="0"/>
<line x1="30" y1="60" x2="270" y2="60" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="5"/>
<line x1="30" y1="90" x2="270" y2="90" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="10"/>
<line x1="30" y1="120" x2="270" y2="120" stroke="#3498db" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="15"/>

负值偏移

负值会让虚线向前偏移,效果与正值相反。

offset: -5 offset: -10 offset: -15
<line x1="30" y1="30" x2="270" y2="30" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="-5"/>
<line x1="30" y1="60" x2="270" y2="60" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="-10"/>
<line x1="30" y1="90" x2="270" y2="90" stroke="#e74c3c" stroke-width="3" stroke-dasharray="10,5" stroke-dashoffset="-15"/>

流动动画

通过CSS动画改变stroke-dashoffset,可以创建虚线流动效果。

向左流动 向右流动 旋转流动
<style>
  .dash-flow {
    stroke-dasharray: 10,5;
    animation: dash-flow 1s linear infinite;
  }
  @keyframes dash-flow {
    to { stroke-dashoffset: -15; }
  }
</style>

<line x1="30" y1="30" x2="270" y2="30" stroke="#3498db" stroke-width="3" class="dash-flow"/>

绘制动画

利用stroke-dasharray和stroke-dashoffset组合,可以实现路径绘制动画效果。

路径绘制动画
<style>
  .draw-line {
    stroke-dasharray: 300;
    stroke-dashoffset: 300;
    animation: draw 2s ease-in-out forwards;
  }
  @keyframes draw {
    to { stroke-dashoffset: 0; }
  }
</style>
<path d="M 30,100 Q 80,30 150,80 T 270,50" fill="none" stroke="#3498db" stroke-width="3" class="draw-line"/>

实际应用

进度指示器

75% 进度环
<style>
  .progress-ring {
    stroke-dasharray: 251.2;
    stroke-dashoffset: 251.2;
    animation: progress 3s ease-out forwards;
  }
  @keyframes progress {
    to { stroke-dashoffset: 62.8; }
  }
</style>

<circle cx="150" cy="75" r="40" fill="none" stroke="#ecf0f1" stroke-width="8"/>
<circle cx="150" cy="75" r="40" fill="none" stroke="#3498db" stroke-width="8" class="progress-ring" transform="rotate(-90 150 75)"/>

加载动画

加载中...
<style>
  .loading {
    stroke-dasharray: 50,200;
    stroke-dashoffset: 0;
    animation: loading 1.5s ease-in-out infinite;
  }
  @keyframes loading {
    50% { stroke-dasharray: 150,50; stroke-dashoffset: -50; }
    100% { stroke-dashoffset: -200; }
  }
</style>

<circle cx="150" cy="60" r="35" fill="none" stroke="#3498db" stroke-width="4" class="loading" transform="rotate(-90 150 60)"/>