vue实现线条动画效果
Vue 实现线条动画效果
在 Vue 中实现线条动画效果可以通过多种方式完成,以下是几种常见的方法:
使用 SVG 和 CSS 动画
SVG 是创建线条动画的理想工具,结合 CSS 动画可以实现平滑的效果。
<template>
<div>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
d="M10 100 Q 100 10 190 100"
fill="none"
stroke="#42b983"
stroke-width="2"
stroke-dasharray="1000"
stroke-dashoffset="1000"
ref="path"
/>
</svg>
</div>
</template>
<script>
export default {
mounted() {
this.$refs.path.style.animation = "dash 3s linear forwards";
},
};
</script>
<style>
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
</style>
使用 GSAP 库
GSAP 是一个强大的动画库,可以轻松实现复杂的线条动画效果。
<template>
<div>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
d="M10 100 Q 100 10 190 100"
fill="none"
stroke="#42b983"
stroke-width="2"
stroke-dasharray="1000"
stroke-dashoffset="1000"
ref="path"
/>
</svg>
</div>
</template>
<script>
import { gsap } from "gsap";
export default {
mounted() {
gsap.to(this.$refs.path, {
strokeDashoffset: 0,
duration: 3,
ease: "power1.inOut",
});
},
};
</script>
使用 Canvas 和 Vue
Canvas 提供了更底层的绘图能力,适合需要高度自定义的线条动画。
<template>
<div>
<canvas ref="canvas" width="200" height="200"></canvas>
</div>
</template>
<script>
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext("2d");
let progress = 0;
const animate = () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(10, 100);
ctx.quadraticCurveTo(100, 10 * progress, 190, 100);
ctx.strokeStyle = "#42b983";
ctx.lineWidth = 2;
ctx.stroke();
if (progress < 1) {
progress += 0.01;
requestAnimationFrame(animate);
}
};
animate();
},
};
</script>
使用 Vue 过渡效果
Vue 的过渡系统可以结合 CSS 实现简单的线条动画。
<template>
<div>
<div class="line-container">
<div class="line" :class="{ 'line-animate': animate }"></div>
</div>
<button @click="animate = !animate">Toggle Animation</button>
</div>
</template>
<script>
export default {
data() {
return {
animate: false,
};
},
};
</script>
<style>
.line-container {
width: 200px;
height: 2px;
background: #ddd;
margin: 20px 0;
}
.line {
height: 100%;
width: 0;
background: #42b983;
transition: width 1s ease;
}
.line-animate {
width: 100%;
}
</style>
使用第三方库(如 anime.js)
anime.js 是一个轻量级的动画库,适合实现复杂的线条动画效果。
<template>
<div>
<svg width="200" height="200" viewBox="0 0 200 200">
<path
d="M10 100 Q 100 10 190 100"
fill="none"
stroke="#42b983"
stroke-width="2"
stroke-dasharray="1000"
stroke-dashoffset="1000"
ref="path"
/>
</svg>
</div>
</template>
<script>
import anime from "animejs";
export default {
mounted() {
anime({
targets: this.$refs.path,
strokeDashoffset: [1000, 0],
duration: 3000,
easing: "easeInOutSine",
});
},
};
</script>
以上方法可以根据具体需求选择适合的实现方式。SVG 和 CSS 动画适合简单的线条动画,GSAP 和 anime.js 适合复杂的动画效果,Canvas 则适合需要高度自定义的场景。







