js实现转盘
实现转盘抽奖功能
使用JavaScript实现转盘抽奖功能需要结合HTML和CSS完成页面布局与动画效果。以下是完整实现方案:
创建HTML结构
<div class="wheel-container">
<div class="wheel">
<div class="wheel-item" data-value="1">奖品1</div>
<div class="wheel-item" data-value="2">奖品2</div>
<div class="wheel-item" data-value="3">奖品3</div>
<div class="wheel-item" data-value="4">奖品4</div>
<div class="wheel-item" data-value="5">奖品5</div>
<div class="wheel-item" data-value="6">奖品6</div>
</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%;
position: relative;
overflow: hidden;
transition: transform 4s cubic-bezier(0.17, 0.67, 0.12, 0.99);
}
.wheel-item {
position: absolute;
width: 50%;
height: 50%;
transform-origin: 100% 100%;
left: 0;
top: 0;
text-align: center;
padding-top: 20px;
box-sizing: border-box;
background: conic-gradient(
from 0deg,
#ff0000 0deg 60deg,
#00ff00 60deg 120deg,
#0000ff 120deg 180deg,
#ffff00 180deg 240deg,
#ff00ff 240deg 300deg,
#00ffff 300deg 360deg
);
}
.spin-btn {
display: block;
margin: 20px auto;
padding: 10px 20px;
background: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
JavaScript实现逻辑
document.querySelector('.spin-btn').addEventListener('click', function() {
const wheel = document.querySelector('.wheel');
const items = document.querySelectorAll('.wheel-item');
const itemCount = items.length;
const anglePerItem = 360 / itemCount;
// 禁用按钮防止重复点击
this.disabled = true;
// 随机选择奖品(0到itemCount-1)
const selectedItem = Math.floor(Math.random() * itemCount);
// 计算旋转角度(多转几圈后停在选定位置)
const extraRotations = 5; // 额外旋转圈数
const targetAngle = 360 * extraRotations + (360 - anglePerItem * selectedItem);
// 应用旋转动画
wheel.style.transform = `rotate(${targetAngle}deg)`;
// 动画结束后启用按钮
setTimeout(() => {
this.disabled = false;
alert(`恭喜获得: ${items[selectedItem].textContent}`);
}, 4000);
});
优化转盘视觉效果
为增强用户体验,可以添加指针和中心固定点:
.wheel-container::before {
content: '';
position: absolute;
width: 20px;
height: 20px;
background: white;
border-radius: 50%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 2;
}
.wheel-container::after {
content: '';
position: absolute;
width: 0;
height: 0;
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-top: 30px solid red;
top: 0;
left: 50%;
transform: translateX(-50%);
z-index: 1;
}
响应式设计调整
使转盘适应不同屏幕尺寸:
@media (max-width: 600px) {
.wheel-container {
width: 200px;
height: 200px;
}
}
注意事项
- 旋转动画使用CSS的transition实现,确保平滑效果
- cubic-bezier时间函数使旋转有缓动效果,更接近真实转盘
- 额外旋转圈数(extraRotations)可根据需要调整
- 实际项目中应将奖品数据从HTML分离,使用JavaScript动态生成转盘项
- 中奖概率可通过调整随机数算法实现不同权重







