js实现抽奖
JavaScript 实现抽奖功能
实现抽奖功能的核心在于随机选择中奖者或奖品,并展示动画效果增强用户体验。以下是几种常见实现方式:
基础随机抽奖
使用 Math.random() 生成随机数选择中奖项:

const prizes = ['一等奖', '二等奖', '三等奖', '谢谢参与'];
function drawLottery() {
const index = Math.floor(Math.random() * prizes.length);
return prizes[index];
}
console.log(drawLottery());
带概率控制的抽奖
为不同奖项设置不同中奖概率:

const prizePool = [
{ name: 'iPhone', prob: 0.01 },
{ name: '红包', prob: 0.2 },
{ name: '谢谢参与', prob: 0.79 }
];
function weightedDraw() {
const random = Math.random();
let cumulativeProb = 0;
for (const prize of prizePool) {
cumulativeProb += prize.prob;
if (random <= cumulativeProb) return prize.name;
}
}
转盘动画效果
结合 CSS 实现视觉动画:
<div id="wheel"></div>
<button onclick="spinWheel()">开始抽奖</button>
<style>
#wheel {
width: 300px;
height: 300px;
border-radius: 50%;
background: conic-gradient(
red 0% 10%,
green 10% 35%,
blue 35% 100%
);
transition: transform 3s cubic-bezier(0.17, 0.85, 0.43, 0.96);
}
</style>
<script>
function spinWheel() {
const wheel = document.getElementById('wheel');
const rotations = 5 + Math.floor(Math.random() * 5);
const degree = 360 * rotations + Math.floor(Math.random() * 360);
wheel.style.transform = `rotate(${degree}deg)`;
setTimeout(() => {
const actualPrize = calculatePrize(degree % 360);
alert(`恭喜获得: ${actualPrize}`);
}, 3000);
}
function calculatePrize(deg) {
if (deg < 36) return '一等奖';
if (deg < 126) return '二等奖';
return '三等奖';
}
</script>
九宫格抽奖
实现常见的跳格动画效果:
let currentIndex = 0;
const blocks = document.querySelectorAll('.block');
function startJump() {
clearInterval(window.jumpInterval);
const targetIndex = Math.floor(Math.random() * 8);
window.jumpInterval = setInterval(() => {
blocks.forEach(b => b.classList.remove('active'));
currentIndex = (currentIndex + 1) % 8;
blocks[currentIndex].classList.add('active');
if (currentIndex === targetIndex) {
clearInterval(window.jumpInterval);
setTimeout(() => alert(`中奖: ${blocks[targetIndex].textContent}`), 500);
}
}, 100);
}
注意事项
- 概率设置需确保总和为 1
- 动画持续时间应与实际抽奖计算同步
- 移动端需考虑触摸事件支持
- 高频率抽奖建议使用
requestAnimationFrame替代setInterval
实际项目中可根据需求组合这些方法,加入开始/停止按钮、奖品计数等完整功能。






