vue实现线条动画效果
使用 SVG 和 CSS 实现线条动画
在 Vue 中实现线条动画可以通过 SVG 结合 CSS 或 JavaScript 动画库完成。SVG 的路径动画效果流畅且易于控制。
定义一个 SVG 路径,通过 stroke-dasharray 和 stroke-dashoffset 属性实现描边动画效果。CSS 关键帧控制动画过程。

<template>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
class="animated-line"
d="M10 100 Q 100 10 190 100"
fill="none"
stroke="#42b983"
stroke-width="2"
/>
</svg>
</template>
<style>
.animated-line {
stroke-dasharray: 500;
stroke-dashoffset: 500;
animation: draw 2s linear forwards;
}
@keyframes draw {
to {
stroke-dashoffset: 0;
}
}
</style>
动态控制动画触发
通过 Vue 的响应式数据或生命周期钩子动态触发动画,例如在组件挂载后开始动画。
<template>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
ref="line"
d="M10 100 Q 100 10 190 100"
fill="none"
stroke="#42b983"
stroke-width="2"
/>
</svg>
</template>
<script>
export default {
mounted() {
const path = this.$refs.line;
const length = path.getTotalLength();
path.style.strokeDasharray = length;
path.style.strokeDashoffset = length;
setTimeout(() => {
path.style.transition = 'stroke-dashoffset 2s ease-in-out';
path.style.strokeDashoffset = '0';
}, 500);
}
};
</script>
使用 GreenSock (GSAP) 库实现复杂动画
对于更复杂的路径动画,GSAP 提供精细的时间轴控制和缓动函数。

<template>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
ref="line"
d="M10 100 Q 100 10 190 100"
fill="none"
stroke="#42b983"
stroke-width="2"
/>
</svg>
</template>
<script>
import { gsap } from 'gsap';
export default {
mounted() {
const path = this.$refs.line;
const length = path.getTotalLength();
gsap.set(path, {
strokeDasharray: length,
strokeDashoffset: length
});
gsap.to(path, {
strokeDashoffset: 0,
duration: 1.5,
ease: "power2.inOut"
});
}
};
</script>
响应式路径数据绑定
通过 Vue 的数据绑定动态更新路径数据,实现交互式线条动画。
<template>
<div>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
:d="pathData"
fill="none"
stroke="#42b983"
stroke-width="2"
ref="line"
/>
</svg>
<button @click="updatePath">更新路径</button>
</div>
</template>
<script>
import { gsap } from 'gsap';
export default {
data() {
return {
pathData: "M10 100 Q 100 10 190 100"
};
},
methods: {
updatePath() {
this.pathData = "M10 50 Q 100 150 190 50";
this.$nextTick(() => {
const path = this.$refs.line;
const length = path.getTotalLength();
gsap.fromTo(path,
{ strokeDashoffset: length },
{ strokeDashoffset: 0, duration: 1 }
);
});
}
}
};
</script>
多段线条顺序动画
通过 GSAP 的时间轴功能实现多段线条的顺序动画效果。
<template>
<svg width="300" height="200" viewBox="0 0 300 200">
<path
v-for="(path, index) in paths"
:key="index"
:ref="`line-${index}`"
:d="path"
fill="none"
stroke="#42b983"
stroke-width="2"
/>
</svg>
</template>
<script>
import { gsap } from 'gsap';
export default {
data() {
return {
paths: [
"M10 50 L100 50",
"M100 50 L100 150",
"M100 150 L200 150"
]
};
},
mounted() {
const tl = gsap.timeline();
this.paths.forEach((_, index) => {
const path = this.$refs[`line-${index}`][0];
const length = path.getTotalLength();
gsap.set(path, {
strokeDasharray: length,
strokeDashoffset: length
});
tl.to(path, {
strokeDashoffset: 0,
duration: 0.8
}, index * 0.3);
});
}
};
</script>






