vue实现飞翔的蝴蝶
实现飞翔的蝴蝶动画
在Vue中实现飞翔的蝴蝶动画,可以通过CSS动画结合动态数据绑定完成。以下是具体实现方法:
使用CSS关键帧动画
定义蝴蝶扇动翅膀的动画效果:
.butterfly {
position: absolute;
width: 50px;
height: 50px;
background-image: url('butterfly.png');
background-size: contain;
animation: fly 0.5s infinite alternate;
}
@keyframes fly {
0% {
transform: rotate(-10deg) translateY(0);
}
100% {
transform: rotate(10deg) translateY(-5px);
}
}
动态控制飞行路径
在Vue组件中使用数据绑定控制蝴蝶位置:
export default {
data() {
return {
position: {
x: 0,
y: 0
},
speed: {
x: 2,
y: 1
}
}
},
mounted() {
this.animateButterfly();
},
methods: {
animateButterfly() {
requestAnimationFrame(() => {
this.position.x += this.speed.x;
this.position.y += this.speed.y;
// 边界检测
if (this.position.x > window.innerWidth) {
this.position.x = 0;
}
if (this.position.y > window.innerHeight) {
this.position.y = 0;
}
this.animateButterfly();
});
}
}
}
模板绑定样式
将动态位置绑定到模板:
<template>
<div
class="butterfly"
:style="{
left: `${position.x}px`,
top: `${position.y}px`,
transform: `rotate(${position.x % 20 - 10}deg)`
}"
></div>
</template>
添加交互效果
可以通过鼠标事件改变蝴蝶飞行方向:
methods: {
handleMouseMove(e) {
const centerX = window.innerWidth / 2;
const centerY = window.innerHeight / 2;
this.speed.x = (e.clientX - centerX) / 100;
this.speed.y = (e.clientY - centerY) / 100;
}
}
使用SVG实现更复杂动画
如果需要更精细的控制,可以使用SVG路径动画:
<template>
<svg>
<path
d="M10 10 Q 50 50, 100 10"
fill="none"
stroke="transparent"
id="butterflyPath"
/>
<image
href="butterfly.svg"
x="-20"
y="-20"
width="40"
height="40"
>
<animateMotion
dur="10s"
repeatCount="indefinite"
path="M10 10 Q 50 50, 100 10"
/>
</image>
</svg>
</template>
这些方法可以组合使用,根据实际需求调整动画效果和交互方式。







