vue红包雨实现
实现思路
红包雨是一种常见的互动效果,通常在节日或促销活动中使用。Vue 结合 Canvas 或 CSS3 动画可以实现这一效果。以下是两种常见的实现方式。
基于 Canvas 的实现
Canvas 适合处理大量动态元素,性能较好。
1. 创建 Canvas 画布
在 Vue 组件中嵌入 Canvas 元素,并设置合适的宽高。
<template>
<div class="red-packet-rain">
<canvas ref="canvas" width="800" height="600"></canvas>
</div>
</template>
2. 初始化 Canvas 上下文
在 mounted 钩子中获取 Canvas 上下文,并初始化红包雨的数据。
export default {
mounted() {
const canvas = this.$refs.canvas;
const ctx = canvas.getContext('2d');
this.initRedPackets(ctx, canvas.width, canvas.height);
},
methods: {
initRedPackets(ctx, width, height) {
this.redPackets = Array.from({ length: 50 }, () => ({
x: Math.random() * width,
y: -20,
speed: 2 + Math.random() * 3,
size: 20 + Math.random() * 10,
}));
this.animate(ctx, width, height);
},
},
};
3. 动画循环
使用 requestAnimationFrame 实现红包下落动画。
animate(ctx, width, height) {
ctx.clearRect(0, 0, width, height);
this.redPackets.forEach(packet => {
packet.y += packet.speed;
if (packet.y > height) {
packet.y = -20;
packet.x = Math.random() * width;
}
ctx.fillStyle = 'red';
ctx.fillRect(packet.x, packet.y, packet.size, packet.size);
});
requestAnimationFrame(() => this.animate(ctx, width, height));
},
基于 CSS3 动画的实现
CSS3 动画实现简单,适合少量元素。
1. 动态生成红包元素
在模板中使用 v-for 动态生成红包元素。
<template>
<div class="red-packet-rain">
<div
v-for="(packet, index) in packets"
:key="index"
class="red-packet"
:style="{
left: `${packet.x}px`,
animation: `fall ${packet.duration}s linear infinite`,
}"
></div>
</div>
</template>
2. 初始化红包数据
在 data 中定义红包的初始位置和动画时间。
export default {
data() {
return {
packets: Array.from({ length: 20 }, () => ({
x: Math.random() * window.innerWidth,
duration: 3 + Math.random() * 4,
})),
};
},
};
3. 定义 CSS 动画
在样式表中定义下落动画和红包样式。
.red-packet-rain {
position: relative;
width: 100%;
height: 100vh;
overflow: hidden;
}
.red-packet {
position: absolute;
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
}
@keyframes fall {
to {
transform: translateY(100vh);
}
}
交互优化
1. 点击红包事件
为红包添加点击事件,点击后移除或触发奖励逻辑。
<div
v-for="(packet, index) in packets"
:key="index"
class="red-packet"
@click="handleClick(index)"
></div>
methods: {
handleClick(index) {
this.packets.splice(index, 1);
alert('恭喜获得红包!');
},
},
2. 性能优化

- Canvas 实现时,避免频繁创建对象,复用红包数据。
- CSS3 实现时,控制红包数量,避免过多 DOM 元素影响性能。
总结
- Canvas 实现:适合复杂场景,性能较好,但代码稍复杂。
- CSS3 实现:简单快捷,适合少量元素,性能受 DOM 数量限制。
根据实际需求选择合适的方案,并优化交互体验。






