JS实现简易转盘抽奖
实现思路
使用HTML、CSS和JavaScript创建一个简易转盘抽奖功能。核心逻辑是通过CSS旋转动画模拟转盘效果,JavaScript控制旋转时间和结果判定。
HTML结构
<div class="wheel-container">
<div class="wheel"></div>
<button id="spin-btn">开始抽奖</button>
<div class="pointer"></div>
</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%,
green 25% 50%,
blue 50% 75%,
yellow 75% 100%
);
transition: transform 4s cubic-bezier(0.17, 0.67, 0.12, 0.99);
transform: rotate(0deg);
}
.pointer {
position: absolute;
top: -20px;
left: 50%;
transform: translateX(-50%);
width: 0;
height: 0;
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-top: 30px solid #333;
}
#spin-btn {
display: block;
margin: 20px auto;
padding: 10px 20px;
background: #333;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
JavaScript逻辑
const wheel = document.querySelector('.wheel');
const spinBtn = document.getElementById('spin-btn');
const segments = 4; // 对应CSS中的颜色分段
let isSpinning = false;
spinBtn.addEventListener('click', () => {
if (isSpinning) return;
isSpinning = true;
const randomRotation = 360 * 5 + Math.floor(Math.random() * 360);
wheel.style.transform = `rotate(${randomRotation}deg)`;
setTimeout(() => {
isSpinning = false;
const actualRotation = randomRotation % 360;
const segmentAngle = 360 / segments;
const winningSegment = Math.floor(actualRotation / segmentAngle);
const colors = ['red', 'green', 'blue', 'yellow'];
alert(`恭喜获得: ${colors[winningSegment]}区域奖品`);
}, 4000);
});
功能扩展建议
- 奖品配置化:将奖品信息存储在数组中,便于修改和管理
- 动画优化:添加开始和结束的缓动效果
- 中奖概率控制:为不同区域设置不同的中奖概率
- 响应式设计:适应不同屏幕尺寸
注意事项
- 确保CSS的transition时间与JavaScript的setTimeout时间一致
- 旋转角度计算需要考虑模360运算,以确定最终停止位置
- 防抖处理防止用户连续点击
- 跨浏览器兼容性测试







