js实现抽奖大圆盘
实现抽奖大圆盘的步骤
创建HTML结构
使用HTML创建一个简单的圆盘结构,包含奖品区域和指针。
<div class="wheel-container">
<div class="wheel" id="wheel"></div>
<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%;
position: relative;
overflow: hidden;
transition: transform 4s cubic-bezier(0.17, 0.67, 0.21, 0.99);
}
.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 red;
z-index: 10;
}
动态生成奖品区域
使用JavaScript动态生成圆盘的奖品扇形区域。

const wheel = document.getElementById('wheel');
const prizes = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6'];
const colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'];
const sectorAngle = 360 / prizes.length;
prizes.forEach((prize, index) => {
const sector = document.createElement('div');
sector.className = 'sector';
sector.style.backgroundColor = colors[index];
sector.style.transform = `rotate(${sectorAngle * index}deg)`;
sector.style.clipPath = `polygon(50% 50%, 50% 0%, ${50 + 50 * Math.cos(sectorAngle * Math.PI / 180)}% ${50 + 50 * Math.sin(sectorAngle * Math.PI / 180)}%)`;
const prizeText = document.createElement('div');
prizeText.className = 'prize-text';
prizeText.textContent = prize;
prizeText.style.transform = `rotate(${sectorAngle / 2}deg)`;
prizeText.style.position = 'absolute';
prizeText.style.top = '20%';
prizeText.style.left = '50%';
sector.appendChild(prizeText);
wheel.appendChild(sector);
});
实现旋转逻辑
添加旋转逻辑,随机决定旋转角度并触发动画。
function spinWheel() {
const spinAngle = 360 * 5 + Math.floor(Math.random() * 360);
wheel.style.transform = `rotate(${-spinAngle}deg)`;
setTimeout(() => {
const actualAngle = spinAngle % 360;
const prizeIndex = Math.floor(actualAngle / sectorAngle);
alert(`恭喜获得:${prizes[prizes.length - 1 - prizeIndex]}`);
}, 4000);
}
document.querySelector('.wheel-container').addEventListener('click', spinWheel);
添加扇形区域的CSS
为扇形区域添加额外的CSS样式,确保文本显示正确。
.sector {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
transform-origin: 50% 50%;
}
.prize-text {
transform-origin: 0 0;
white-space: nowrap;
font-size: 12px;
color: white;
text-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
}
注意事项
- 圆盘的旋转角度通过随机数生成,确保每次旋转结果不同。
- 使用
cubic-bezier动画曲线模拟真实的旋转减速效果。 - 扇形区域的计算需要用到三角函数,确保每个扇形的角度均匀分布。
- 实际项目中可以将奖品和颜色配置为动态数据,通过接口获取。






