效果展示
步驟分解
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;
}