uniapp红包雨活动
template
<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
<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
<!-- 红包雨活动 -->
<style lang="scss">
.red-envelope-rain {
position: relative;
overflow: hidden;
width: 100vw;
height: 100vh;
}
.red-envelope {
position: absolute;
background-image: url('自己的红包图片');
background-size: 100rpx 100rpx;
background-repeat: no-repeat;
width: 100rpx;
height: 100rpx;
}
</style>