動態

詳情 返回 返回

給線條類型的svg圖標加上繪製的動畫效果 - 動態 詳情

效果展示

chrome-capture-2024-10-2.gif

步驟分解

1 確認svg文件有路徑數據
2 獲取path的長度
3 定義繪製線條的長度
4 定義關鍵幀動畫
5 應用關鍵幀動畫

實操

1 確認svg文件有路徑數據
path標籤裏面的d屬性,就是路徑數據

<template>
  <svg fill="none" xmlns="http://www.w3.org/2000/svg" width="260" height="300" viewBox="0 0 260 300">
    <path
      ref="pathRef"
      class="path"
      stroke="#000"
      stroke-width="5"
      stroke-linecap="round"
      d="..."
    />
  </svg>
</template>

2 獲取path的長度
調用SVGPathElement上的getTotalLength方法,獲取線條的長度

<template>
  <svg fill="none" xmlns="http://www.w3.org/2000/svg" width="260" height="300" viewBox="0 0 260 300">
    <path
      ref="pathRef"
      class="path"
      stroke="#000"
      stroke-width="5"
      stroke-linecap="round"
      d="..."
      />
  </svg>
</template>

<script setup lang='ts'>
  import { onMounted, ref } from 'vue';
  const pathRef = ref<SVGPathElement | null>(null);

  onMounted(() => {
    const value = pathRef.value?.getTotalLength()
    console.log(value)
    // 842.6114501953125
  })
</script>

3 定義繪製線條的長度
把從getTotalLength獲取的線條長度賦值給線條

<template>
  <svg fill="none" xmlns="http://www.w3.org/2000/svg" width="260" height="300" viewBox="0 0 260 300">
    <path
      ref="pathRef"
      class="path"
      stroke="#000"
      stroke-width="5"
      stroke-linecap="round"
      d="..."
      />
  </svg>
</template>

<style lang='less' scoped>
  .path {
    stroke-dasharray: 843px;
  }
</style>

4 定義關鍵幀動畫
分別設置起始幀狀態和結束幀狀態

@keyframes drawLine {
  from {
    /* 起始幀給線條加上等於自身長度的偏移,使線條不可見 */
    stroke-dashoffset: 842px;
  }
  to {
    /* 結束幀讓偏移值為0,使得線條完整可見 */
    stroke-dashoffset: 0px;
  }
}

5 應用關鍵幀動畫
將定義的keyframes賦值給animation

<template>
  <svg fill="none" xmlns="http://www.w3.org/2000/svg" width="260" height="300" viewBox="0 0 260 300">
    <path
      ref="pathRef"
      class="path"
      stroke="#000"
      stroke-width="5"
      stroke-linecap="round"
      d="..."
    />
  </svg>
</template>

<style lang='less' scoped>
@keyframes drawLine {
  from {
    stroke-dashoffset: 843px;
  }
  to {
    stroke-dashoffset: 0px;
  }
}

.path {
  stroke-dasharray: 843px;
  /* 應用關鍵幀動畫 */
  animation: drawLine 3s ease-out;
  /* 動畫結束時,將元素保留在最後一幀的狀態,也就是線條可見的狀態 */
  animation-fill-mode: forwards;
}
</style>

關於兼容性

測試下來發現用animation來操作stroke-dashoffset的兼容性不佳,最後換成transition了,兼容性要好很多。

.path {
  stroke-dasharray: 843px;
  stroke-dashoffset: 843px;
  transition: stroke-dashoffset 3s ease-in-out
}

.draw {
  stroke-dashoffset: 0;
}
user avatar zs_staria 頭像 jingdongkeji 頭像 woniuseo 頭像 joe235 頭像 yishidemeihao_5b9ce075877c9 頭像 ldh-blog 頭像 xiao2 頭像 jmix 頭像 junxiudetuoba 頭像 songxianling1992 頭像 baidujiagoushi 頭像 robin_ren 頭像
點贊 12 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.