vue实现飞翔的蝴蝶
实现思路
在Vue中实现飞翔的蝴蝶动画,可以通过CSS动画结合动态数据绑定完成。核心是利用@keyframes定义蝴蝶翅膀扇动和飞行路径,通过Vue的响应式数据控制动画状态。
基础HTML结构
<template>
<div class="scene">
<div class="butterfly" :style="butterflyStyle">
<div class="wings left-wing"></div>
<div class="wings right-wing"></div>
</div>
</div>
</template>
CSS动画设计
.scene {
position: relative;
width: 100vw;
height: 100vh;
overflow: hidden;
background: skyblue;
}
.butterfly {
position: absolute;
width: 50px;
height: 50px;
transform-origin: center;
}
.wings {
position: absolute;
width: 20px;
height: 40px;
background: linear-gradient(45deg, #ff00ff, #ff1493);
border-radius: 50%;
}
.left-wing {
left: 0;
transform-origin: right center;
animation: flap 0.5s infinite alternate;
}
.right-wing {
right: 0;
transform-origin: left center;
animation: flap 0.5s infinite alternate-reverse;
}
@keyframes flap {
0% { transform: rotateY(0deg); }
100% { transform: rotateY(70deg); }
}
@keyframes fly {
0% { transform: translate(0, 0) rotate(0deg); }
25% { transform: translate(200px, 100px) rotate(20deg); }
50% { transform: translate(400px, 50px) rotate(0deg); }
75% { transform: translate(600px, 150px) rotate(-20deg); }
100% { transform: translate(800px, 0) rotate(0deg); }
}
Vue动画控制
<script>
export default {
data() {
return {
position: { x: 0, y: 0 },
angle: 0,
flightPath: []
}
},
computed: {
butterflyStyle() {
return {
transform: `translate(${this.position.x}px, ${this.position.y}px) rotate(${this.angle}deg)`,
animation: 'fly 10s infinite linear'
}
}
},
mounted() {
this.generateFlightPath()
},
methods: {
generateFlightPath() {
// 生成随机飞行路径点
this.flightPath = Array.from({ length: 5 }, () => ({
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight
}))
}
}
}
</script>
高级实现方案
对于更复杂的飞行轨迹,可以使用GSAP动画库:

-
安装GSAP

npm install gsap -
实现贝塞尔曲线飞行
import { gsap } from 'gsap'
methods: { startAnimation() { gsap.to(this.position, { duration: 10, x: this.flightPath.map(p => p.x), y: this.flightPath.map(p => p.y), ease: "sine.inOut", modifiers: { x: gsap.utils.unitize(x => parseFloat(x) + 'px'), y: gsap.utils.unitize(y => parseFloat(y) + 'px') }, repeat: -1 }) } }
### 性能优化建议
- 使用`will-change: transform`提升动画性能
- 对翅膀使用`transform-style: preserve-3d`
- 在移动端考虑减少动画复杂度
- 使用`requestAnimationFrame`进行手动动画控制






