JS实现简易转盘抽奖

实现思路
使用HTML+CSS构建转盘界面,通过JavaScript控制旋转动画和抽奖逻辑。核心是计算旋转角度和动画时间,模拟物理减速效果。

HTML结构
<div class="wheel-container">
<div class="wheel"></div>
<button class="spin-btn">开始抽奖</button>
</div>
CSS样式
.wheel-container {
position: relative;
width: 300px;
height: 300px;
margin: 0 auto;
}
.wheel {
width: 100%;
height: 100%;
border-radius: 50%;
background: conic-gradient(
red 0% 25%,
blue 25% 50%,
green 50% 75%,
yellow 75% 100%
);
transition: transform 4s cubic-bezier(0.17, 0.67, 0.12, 0.99);
}
.spin-btn {
display: block;
margin: 20px auto;
padding: 10px 20px;
background: #3498db;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
JavaScript逻辑
const wheel = document.querySelector('.wheel');
const spinBtn = document.querySelector('.spin-btn');
let canSpin = true;
// 奖项配置
const prizes = ['一等奖', '二等奖', '三等奖', '谢谢参与'];
const prizeAngles = [0, 90, 180, 270]; // 各奖项对应的角度
spinBtn.addEventListener('click', () => {
if (!canSpin) return;
canSpin = false;
const randomIndex = Math.floor(Math.random() * prizes.length);
const targetAngle = 360 * 5 + prizeAngles[randomIndex]; // 旋转5圈后停在目标位置
wheel.style.transform = `rotate(${-targetAngle}deg)`;
setTimeout(() => {
alert(`恭喜获得: ${prizes[randomIndex]}`);
canSpin = true;
}, 4000);
});
优化方向
- 添加指针元素指向中奖区域
- 实现更真实的减速动画效果
- 增加音效增强体验
- 支持动态配置奖项数量和颜色
- 添加旋转过程中的状态提示
物理减速实现
使用CSS的cubic-bezier缓动函数模拟物理减速效果:
transition: transform 4s cubic-bezier(0.17, 0.67, 0.12, 0.99);
兼容性提示
现代浏览器都支持上述技术,如需兼容旧版IE,需考虑使用jQuery动画替代CSS过渡。






