vue3 画一只漂亮的会飞的蝴蝶
时间: 2023-10-19 18:13:31 浏览: 79
好的,以下是一个简单的Vue组件代码,可以实现画一只漂亮的会飞的蝴蝶的效果:
```vue
<template>
<div class="butterfly-container">
<div class="butterfly" :style="{ top: butterflyTop + 'px', left: butterflyLeft + 'px' }" ref="butterfly">
<div class="butterfly-body"></div>
<div class="butterfly-wing butterfly-wing-left"></div>
<div class="butterfly-wing butterfly-wing-right"></div>
</div>
</div>
</template>
<script>
export default {
name: "Butterfly",
data() {
return {
butterflyTop: 0,
butterflyLeft: 0,
direction: "right",
flyInterval: null
}
},
mounted() {
this.fly();
},
beforeUnmount() {
clearInterval(this.flyInterval);
},
methods: {
fly() {
this.flyInterval = setInterval(() => {
let butterfly = this.$refs.butterfly;
let container = butterfly.parentNode;
let containerWidth = container.offsetWidth;
let containerHeight = container.offsetHeight;
let butterflyWidth = butterfly.offsetWidth;
let butterflyHeight = butterfly.offsetHeight;
let butterflyTop = this.butterflyTop;
let butterflyLeft = this.butterflyLeft;
if (this.direction === "right") {
butterflyLeft += 5;
butterfly.style.transform = "rotateY(0deg)";
if (butterflyLeft >= containerWidth - butterflyWidth) {
this.direction = "left";
}
} else {
butterflyLeft -= 5;
butterfly.style.transform = "rotateY(180deg)";
if (butterflyLeft <= 0) {
this.direction = "right";
}
}
butterflyTop += Math.sin(butterflyLeft / 50) * 10;
butterfly.style.top = butterflyTop + "px";
butterfly.style.left = butterflyLeft + "px";
if (butterflyTop >= containerHeight - butterflyHeight) {
this.butterflyTop = containerHeight - butterflyHeight;
} else {
this.butterflyTop = butterflyTop;
}
this.butterflyLeft = butterflyLeft;
}, 50);
}
}
}
</script>
<style>
.butterfly-container {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
}
.butterfly {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.butterfly-body {
position: absolute;
top: 0;
left: 0;
width: 30px;
height: 30px;
background-color: #f39c12;
border-radius: 50%;
z-index: 3;
}
.butterfly-wing {
position: absolute;
top: 0;
width: 60px;
height: 60px;
background-color: #f39c12;
border-radius: 50%;
transform-origin: center;
z-index: 2;
}
.butterfly-wing-left {
left: -30px;
transform: rotate(-45deg);
}
.butterfly-wing-right {
right: -30px;
transform: rotate(45deg);
}
@keyframes butterfly-flap {
0% {
transform: rotate(0deg);
}
50% {
transform: rotate(20deg);
}
100% {
transform: rotate(0deg);
}
}
</style>
```
你可以把这段代码复制到一个.vue文件中,然后使用Vue的方式来引入和使用这个组件。注意,为了让这个组件能够正常工作,你需要在项目中引入一个CSS动画库,比如Animate.css。这个蝴蝶会在容器中飞行,并且会随着水平方向的移动而上下浮动。你可以根据需要调整蝴蝶的大小和颜色,以及飞行的速度和浮动的幅度。
阅读全文