Skip to content

SVG 描边动画 ​

SVG 描边动画的原理是使用其 stroke-dasharray 和 stoke-dashoffset 属性。

描边虚线模式 ​

stroke-dasharray 可定义描边虚线,具体是要指定实线宽度和间隔宽度。

若为一个值则表示实线和间隔宽度都是该值:

stroke-dasharray: "5"

若为两个值,则第一个值表示实线宽度,第二个值表示间隔宽度:

stroke-dasharray: "10 5"

若为多个值,则会按此序列循环,如“10 5 2”则会为“10 5 2 10 5 2 10 5 2 ...”,就会按实线 10px,间隔 5px,实线 2px,间隔 10px 如此循环。

stroke-dasharray: "10 5 2"

描边虚线偏移 ​

stroke-dashoffset 定义虚线模式的起始位置。当偏移量大于等于描边路径总长度时,描边就会消失,然后通过给 stroke-dashoffset 添加动画,让其逐渐变为 0,就可呈现出路径动画效果。

路径总长度可通过 JS 获取,获取 <rect> 或 <path> 等 svg 标签元素后,调用其 getTotalLength() 即可获得路径总长度。

html
<svg width="320" height="300" viewBox="0 0 320 300">
  <path
    d="M160 260 L60 160 C0 90 100 0 160 60 C210 0 325 80 260 160 L160 260"
    stroke="#f03752"
    stroke-width="2"
    stroke-linecap="round"
    stroke-linejoin="round"
    stroke-dasharray="718"
    stroke-dashoffset="718"
    fill="none"
  >
    <animate 
      attributeName="stroke-dashoffset"
      to="0"
      begin="0"
      dur="3s"
      repeatCount="indefinite"
    />
  </path>
</svg>

应用 CSS 动画 ​

以上示例是使用 SVG 的 SMIL 动画,是一组内置在 SVG 中用于创建动画的 XML 标签。

动画效果也可用 CSS animation 来实现。

html
<svg width="300" height="300" viewBox="0 0 300 300">
  <path d="M40 220 L150 20"
    stroke="#bd34fe" stroke-width="2"
    stroke-dasharray="228" stroke-dashoffset="228"
  />
  <path d="M150 20 L260 220"
    stroke="#bd34fe" stroke-width="2"
    stroke-dasharray="228" stroke-dashoffset="228"
  />
  <path d="M260 220 L40 220"
    stroke="#bd34fe" stroke-width="2"
    stroke-dasharray="220" stroke-dashoffset="220"
  />
  <path d="M40 80 L260 80"
    stroke="#bd34fe" stroke-width="2"
    stroke-dasharray="220" stroke-dashoffset="220"
  />
  <path d="M260 80 L150 280"
    stroke="#bd34fe" stroke-width="2"
    stroke-dasharray="228" stroke-dashoffset="228"
  />
  <path d="M150 280 L40 80"
    stroke="#bd34fe" stroke-width="2"
    stroke-dasharray="228" stroke-dashoffset="228"
  />
</svg>
css
path {
  animation: stroke-offset 3s infinite;
}
@keyframes stroke-offset {
  to { stroke-dashoffset: 0 }
}

文字描边 ​

只要是描边都可应用以上效果,不管是文字还是复杂图案,可先通过 Adobe Illustrator 等软件来创建 svg 图片。