js实现大转盘
实现大转盘的基本思路
大转盘的实现主要依赖CSS动画和JavaScript控制逻辑。核心是通过旋转角度计算奖品位置,结合动画效果模拟转盘转动。
HTML结构搭建
创建一个包含转盘和指针的HTML结构。转盘通常使用div元素,奖品区域用列表或绝对定位的子元素实现。
<div class="wheel">
<div class="wheel-items">
<div class="wheel-item" style="--i:1">奖品1</div>
<div class="wheel-item" style="--i:2">奖品2</div>
<!-- 更多奖品项 -->
</div>
<div class="pointer"></div>
</div>
CSS样式设计
使用CSS定义转盘外观和初始状态。关键点包括圆形布局、奖品项的角度分布和指针样式。
.wheel {
position: relative;
width: 300px;
height: 300px;
border-radius: 50%;
overflow: hidden;
}
.wheel-items {
width: 100%;
height: 100%;
position: relative;
}
.wheel-item {
position: absolute;
width: 50%;
height: 50%;
transform-origin: bottom right;
left: 0;
top: 0;
transform: rotate(calc(45deg * var(--i)));
}
JavaScript控制逻辑
实现旋转动画和停止逻辑。核心是通过transform属性的动态修改实现旋转效果。
const wheel = document.querySelector('.wheel');
let isRotating = false;
function startRotation() {
if(isRotating) return;
isRotating = true;
const duration = 3000; // 旋转持续时间
const rotations = 5; // 旋转圈数
wheel.style.transition = `transform ${duration}ms cubic-bezier(0.17,0.89,0.32,1.27)`;
wheel.style.transform = `rotate(${360 * rotations}deg)`;
setTimeout(() => {
isRotating = false;
// 这里添加结果处理逻辑
}, duration);
}
奖品定位算法
根据旋转角度计算最终停下的奖品。需要考虑旋转圈数后的精确位置。
function getPrizeIndex(totalDegrees) {
const segmentAngle = 360 / prizeCount;
const normalizedAngle = totalDegrees % 360;
return Math.floor(normalizedAngle / segmentAngle);
}
动画优化技巧
添加缓动函数使旋转更自然,使用will-change属性提升性能。
.wheel {
will-change: transform;
transition: transform 3s cubic-bezier(0.17,0.89,0.32,1.27);
}
完整实现示例
结合所有要素的完整代码示例,包含事件绑定和结果处理。
document.querySelector('.pointer').addEventListener('click', () => {
const prizeIndex = Math.floor(Math.random() * 8); // 随机选择奖品
const segmentAngle = 360 / 8;
const targetAngle = 360 * 5 + (360 - segmentAngle * prizeIndex);
wheel.style.transform = `rotate(${targetAngle}deg)`;
setTimeout(() => {
alert(`恭喜获得: 奖品${prizeIndex + 1}`);
}, 3000);
});






