js 实现转盘
JavaScript 实现转盘效果
创建 HTML 结构
<div class="wheel-container">
<div class="wheel"></div>
<button id="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);
}
.spin-btn {
margin-top: 20px;
padding: 10px 20px;
font-size: 16px;
}
JavaScript 实现旋转逻辑
const wheel = document.querySelector('.wheel');
const spinBtn = document.getElementById('spin-btn');
const segments = 8; // 转盘分段数
const colors = ['#FF0000', '#FF7F00', '#FFFF00', '#00FF00', '#0000FF', '#4B0082', '#9400D3', '#FF1493'];
// 创建转盘扇形
function createWheel() {
const angle = 360 / segments;
for (let i = 0; i < segments; i++) {
const segment = document.createElement('div');
segment.style.position = 'absolute';
segment.style.width = '50%';
segment.style.height = '50%';
segment.style.transformOrigin = '100% 100%';
segment.style.transform = `rotate(${angle * i}deg) skewY(${90 - angle}deg)`;
segment.style.backgroundColor = colors[i];
wheel.appendChild(segment);
}
}
// 旋转转盘
function spinWheel() {
const spinDegrees = 360 * 5 + Math.floor(Math.random() * 360);
wheel.style.transform = `rotate(${spinDegrees}deg)`;
spinBtn.disabled = true;
setTimeout(() => {
spinBtn.disabled = false;
const winningSegment = Math.floor(((spinDegrees % 360) / 360) * segments);
alert(`恭喜获得: ${winningSegment + 1}号奖品`);
}, 4000);
}
createWheel();
spinBtn.addEventListener('click', spinWheel);
进阶优化方案
-
添加指针元素

<div class="pointer"></div>.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 #000; z-index: 10; } -
添加奖品标签

function addPrizeLabels() { const angle = 360 / segments; const radius = 150;
for (let i = 0; i < segments; i++) { const label = document.createElement('div'); const radian = (angle i + angle / 2) Math.PI / 180; const x = radius 0.7 Math.cos(radian); const y = radius 0.7 Math.sin(radian);
label.textContent = `奖品${i+1}`;
label.style.position = 'absolute';
label.style.left = `calc(50% + ${x}px)`;
label.style.top = `calc(50% + ${y}px)`;
label.style.transform = 'translate(-50%, -50%)';
wheel.appendChild(label);
} }
3. 添加音效
```javascript
function playSpinSound() {
const audio = new Audio('spin-sound.mp3');
audio.play();
}
注意事项
- 确保转盘容器设置为相对定位
- 旋转动画使用CSS transition实现平滑效果
- 计算获奖区域时要考虑旋转总圈数
- 移动端适配需要额外处理触摸事件
- 性能优化可考虑使用CSS硬件加速






