js红包雨实现
实现红包雨的基本思路
红包雨是一种常见的互动效果,通常用于节日活动或营销场景。通过 JavaScript 可以实现动态生成红包、控制下落动画以及交互逻辑。
核心代码结构
HTML 部分需要准备一个容器用于承载红包元素:
<div id="redpacket-container"></div>
CSS 部分定义红包样式和动画效果:
.redpacket {
position: absolute;
width: 60px;
height: 80px;
background-image: url('redpacket.png');
background-size: contain;
cursor: pointer;
animation: fall linear;
}
@keyframes fall {
to {
transform: translateY(100vh);
}
}
JavaScript 实现逻辑
初始化红包雨参数:
const config = {
duration: 10000, // 动画持续时间
frequency: 300, // 红包生成频率(ms)
quantity: 30 // 红包总数
};
创建红包元素函数:
function createRedPacket() {
const packet = document.createElement('div');
packet.className = 'redpacket';
packet.style.left = `${Math.random() * window.innerWidth}px`;
packet.style.animationDuration = `${Math.random() * 3 + 2}s`;
packet.addEventListener('click', () => {
packet.remove();
// 添加点击后的逻辑
});
document.getElementById('redpacket-container').appendChild(packet);
setTimeout(() => {
packet.remove();
}, config.duration);
}
控制红包生成节奏:
let count = 0;
const interval = setInterval(() => {
if(count >= config.quantity) {
clearInterval(interval);
return;
}
createRedPacket();
count++;
}, config.frequency);
高级功能扩展
-
实现红包分层效果:
// 在createRedPacket函数中添加 packet.style.zIndex = Math.floor(Math.random() * 3); -
添加旋转动画:
@keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.redpacket { animation: fall linear, rotate 5s linear infinite; }
3. 实现碰撞检测:
```javascript
// 需要添加物理引擎或使用边界检测算法
function checkCollision(element1, element2) {
const rect1 = element1.getBoundingClientRect();
const rect2 = element2.getBoundingClientRect();
return !(
rect1.right < rect2.left ||
rect1.left > rect2.right ||
rect1.bottom < rect2.top ||
rect1.top > rect2.bottom
);
}
性能优化建议
使用对象池管理红包元素避免频繁创建销毁:
const packetPool = [];
function getPacketFromPool() {
return packetPool.length ?
packetPool.pop() :
document.createElement('div');
}
function returnPacketToPool(packet) {
packetPool.push(packet);
}
使用requestAnimationFrame优化动画:
function animate() {
// 更新所有红包位置
requestAnimationFrame(animate);
}
animate();
移动端适配方案
添加触摸事件支持:
packet.addEventListener('touchstart', (e) => {
e.preventDefault();
// 处理触摸逻辑
});
调整红包大小适应不同屏幕:
const size = Math.min(window.innerWidth, window.innerHeight) * 0.1;
packet.style.width = `${size}px`;
packet.style.height = `${size * 1.3}px`;






