js实现转盘抽奖
实现转盘抽奖的步骤
HTML 结构 创建一个包含转盘和抽奖按钮的基本HTML结构。转盘通常是一个圆形区域,划分为多个扇形区域,每个区域对应一个奖项。
<div class="wheel-container">
<div class="wheel"></div>
<button id="spin-btn">开始抽奖</button>
</div>
CSS 样式
使用CSS绘制转盘,并为每个扇形区域设置不同的颜色和文字。通过transform属性实现旋转效果。
.wheel-container {
position: relative;
width: 300px;
height: 300px;
margin: 0 auto;
}
.wheel {
width: 100%;
height: 100%;
border-radius: 50%;
position: relative;
overflow: hidden;
transition: transform 4s cubic-bezier(0.17, 0.67, 0.12, 0.99);
}
.slice {
position: absolute;
width: 50%;
height: 50%;
transform-origin: 100% 100%;
left: 0;
top: 0;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
}
#spin-btn {
margin-top: 20px;
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
JavaScript 逻辑 使用JavaScript动态生成转盘扇形区域,并实现旋转逻辑。通过随机数决定最终停止的角度。
document.addEventListener('DOMContentLoaded', function() {
const wheel = document.querySelector('.wheel');
const spinBtn = document.getElementById('spin-btn');
const prizes = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6'];
const colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'];
let currentRotation = 0;
let isSpinning = false;
// 创建扇形区域
prizes.forEach((prize, index) => {
const slice = document.createElement('div');
slice.className = 'slice';
slice.style.backgroundColor = colors[index];
slice.style.transform = `rotate(${(360 / prizes.length) * index}deg) skewY(${90 - (360 / prizes.length)}deg)`;
slice.textContent = prize;
wheel.appendChild(slice);
});
// 点击抽奖按钮
spinBtn.addEventListener('click', function() {
if (isSpinning) return;
isSpinning = true;
// 随机决定旋转角度
const randomAngle = Math.floor(Math.random() * 360) + 1440; // 1440表示至少旋转4圈
currentRotation += randomAngle;
// 应用旋转
wheel.style.transform = `rotate(${currentRotation}deg)`;
// 旋转结束后重置状态
setTimeout(() => {
isSpinning = false;
const prizeIndex = Math.floor(((currentRotation % 360) / 360) * prizes.length);
alert(`恭喜获得: ${prizes[prizeIndex]}`);
}, 4000);
});
});
关键点说明
旋转动画
使用CSS的transition属性实现平滑旋转效果。cubic-bezier函数用于自定义缓动效果,使旋转更自然。
奖项计算
通过模运算currentRotation % 360获取最终停止的角度,再根据角度计算对应的奖项索引。
防重复点击
通过isSpinning标志防止用户在旋转过程中重复点击按钮,确保每次抽奖完整执行。
动态生成扇形 使用JavaScript动态创建扇形区域,便于后期修改奖项数量和内容,提高代码灵活性。
扩展功能
添加音效 在旋转开始和结束时播放音效,增强用户体验。
const spinSound = new Audio('spin-sound.mp3');
const winSound = new Audio('win-sound.mp3');
spinBtn.addEventListener('click', function() {
spinSound.play();
// ...旋转逻辑
setTimeout(() => {
winSound.play();
}, 4000);
});
自定义奖项概率 通过权重数组实现不同奖项的中奖概率控制。

const prizeWeights = [10, 20, 30, 20, 15, 5]; // 各奖项权重
function getRandomPrizeIndex() {
const totalWeight = prizeWeights.reduce((a, b) => a + b, 0);
let random = Math.random() * totalWeight;
for (let i = 0; i < prizeWeights.length; i++) {
if (random < prizeWeights[i]) return i;
random -= prizeWeights[i];
}
}






