文章目录
- 1. 页面效果
- 2. 页面样式代码
1. 页面效果
GIF录屏有点卡,实际比较丝滑
- 每0.5s掉落一个红包
- 控制4s后自动移除红包
- 点击红包消除红包(或者自行+1,或者弹窗需求)
2. 页面样式代码
<!-- 红包雨活动 -->
<template>
<scroll-view scroll-y="true">
<view class="red-envelope-rain">
<view v-for="(redEnvelope, index) in redEnvelopes" :key="index" class="red-envelope"
:style="{ top: redEnvelope.top + 'px', left: redEnvelope.left + 'px' }"
@click="handleRedEnvelopeClick(index)"></view>
</view>
</scroll-view>
</template>
<script>
export default {
data() {
return {
redEnvelopes: [],
redEnvelopeInterval: null,
}
},
onLoad(options) {
// 每秒创建一个红包
setInterval(this.initializeRedEnvelopes, 500);
// 更新红包位置,约 60 帧
setInterval(this.moveRedEnvelopes, 1000 / 60);
},
beforeDestroy() {
this.stopRedEnvelopeRain();
},
methods: {
initializeRedEnvelopes() {
const numRedEnvelopes = 20; // 红包数量
// for (let i = 0; i < numRedEnvelopes; i++) {
const redEnvelope = {
id: Date.now(),
top: 0, // 随机纵坐标
left: Math.random() * (uni.getSystemInfoSync().windowWidth - 50), // 随机横坐标
speed: Math.random() * 6 + 1, // 随机速度
};
this.redEnvelopes.push(redEnvelope);
setTimeout(() => {
this.redEnvelopes = this.redEnvelopes.filter(p => p.id !== redEnvelope.id);
}, 4000); // 4秒后移除红包
},
startRedEnvelopeRain() {
this.redEnvelopeInterval = setInterval(() => {
this.moveRedEnvelopes();
}, 1000 / 60); // 每秒60帧
},
stopRedEnvelopeRain() {
clearInterval(this.redEnvelopeInterval);
},
moveRedEnvelopes() {
this.redEnvelopes.forEach((redEnvelope, index) => {
console.log(redEnvelope, "redEnvelopes")
redEnvelope.top += redEnvelope.speed;
if (redEnvelope.top > uni.getSystemInfoSync().windowHeight) {
this.redEnvelopes = this.redEnvelopes.filter(p => p.id !== redEnvelope.id);
}
});
},
// 处理红包点击事件,可以增加分数或显示提示等操作
handleRedEnvelopeClick(index) {
// 例如:this.score += 1;
// 或者:this.showTip = true;
// 可以根据实际需求自行添加逻辑
this.redEnvelopes.splice(index, 1); // 点击后移除红包
},
}
}
</script>
<style lang="scss">
.red-envelope-rain {
position: relative;
overflow: hidden;
width: 100vw;
height: 100vh;
}
.red-envelope {
position: absolute;
background-image: url('https://i-1.lanrentuku.com/2020/11/4/a9b4bcdb-75f3-429d-9c21-d83d945b088e.png?imageView2/2/w/500');
background-size: 100rpx 100rpx;
background-repeat: no-repeat;
width: 100rpx;
height: 100rpx;
}
</style>