抽奖 js实现
实现抽奖功能的JavaScript方法
基础抽奖逻辑
使用Math.random()生成随机数,结合奖品权重实现抽奖逻辑。以下是一个简单实现:
function drawPrize(prizes) {
const totalWeight = prizes.reduce((sum, prize) => sum + prize.weight, 0);
const randomNum = Math.random() * totalWeight;
let weightSum = 0;
for (const prize of prizes) {
weightSum += prize.weight;
if (randomNum <= weightSum) return prize;
}
}
奖品配置示例
const prizes = [
{ name: "一等奖", weight: 1 },
{ name: "二等奖", weight: 3 },
{ name: "三等奖", weight: 10 },
{ name: "参与奖", weight: 86 }
];
转盘动画实现
结合CSS动画和JavaScript控制抽奖结果:
const wheel = document.getElementById('wheel');
let isRotating = false;
function startDraw() {
if (isRotating) return;
isRotating = true;
const resultIndex = Math.floor(Math.random() * prizes.length);
const rotation = 3600 + (360 / prizes.length) * resultIndex;
wheel.style.transition = 'transform 4s ease-out';
wheel.style.transform = `rotate(${rotation}deg)`;
setTimeout(() => {
alert(`恭喜获得: ${prizes[resultIndex].name}`);
isRotating = false;
}, 4000);
}
概率控制方法
对于需要精确控制概率的场景,可以使用预生成结果池:

function createPrizePool(prizes) {
const pool = [];
prizes.forEach(prize => {
for (let i = 0; i < prize.weight; i++) {
pool.push(prize);
}
});
return pool;
}
const prizePool = createPrizePool(prizes);
function drawFromPool() {
const randomIndex = Math.floor(Math.random() * prizePool.length);
return prizePool[randomIndex];
}
九宫格抽奖实现
const blocks = document.querySelectorAll('.block');
let currentIndex = 0;
let timer = null;
function startBlockDraw() {
clearInterval(timer);
let speed = 100;
const totalSteps = 30 + Math.floor(Math.random() * 20);
let steps = 0;
timer = setInterval(() => {
blocks.forEach(b => b.classList.remove('active'));
blocks[currentIndex].classList.add('active');
currentIndex = (currentIndex + 1) % blocks.length;
steps++;
if (steps > totalSteps / 2) speed += 20;
if (steps >= totalSteps) {
clearInterval(timer);
announceResult();
}
}, speed);
}
注意事项
- 移动端需考虑触摸事件支持
- 抽奖结果应通过服务器验证防止作弊
- 动画时间不宜过短影响用户体验
- 中奖概率需符合相关法律法规要求
以上方法可根据实际需求组合使用,核心是通过随机数生成决定抽奖结果,配合动画增强用户体验。






