java js实现转盘抽奖
实现转盘抽奖的步骤
HTML结构
创建转盘抽奖的基本HTML结构,包括转盘区域和抽奖按钮。

<div id="wheel">
<canvas id="wheelCanvas"></canvas>
<button id="spinButton">开始抽奖</button>
</div>
CSS样式
添加CSS样式,使转盘居中显示并美化按钮。
#wheel {
text-align: center;
margin-top: 50px;
}
#wheelCanvas {
border: 1px solid #ccc;
border-radius: 50%;
}
#spinButton {
margin-top: 20px;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
JavaScript逻辑
使用JavaScript绘制转盘并实现抽奖逻辑。
document.addEventListener('DOMContentLoaded', function() {
const canvas = document.getElementById('wheelCanvas');
const ctx = canvas.getContext('2d');
const spinButton = document.getElementById('spinButton');
const prizes = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6'];
const colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'];
let currentAngle = 0;
let spinning = false;
// 设置画布大小
canvas.width = 400;
canvas.height = 400;
// 绘制转盘
function drawWheel() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
const radius = Math.min(centerX, centerY) - 10;
const anglePerPrize = (2 * Math.PI) / prizes.length;
// 绘制扇形
for (let i = 0; i < prizes.length; i++) {
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, i * anglePerPrize + currentAngle, (i + 1) * anglePerPrize + currentAngle);
ctx.fillStyle = colors[i % colors.length];
ctx.fill();
ctx.closePath();
// 绘制文字
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(i * anglePerPrize + anglePerPrize / 2 + currentAngle);
ctx.textAlign = 'right';
ctx.fillStyle = '#fff';
ctx.font = '16px Arial';
ctx.fillText(prizes[i], radius - 10, 5);
ctx.restore();
}
}
// 旋转转盘
function spinWheel() {
if (spinning) return;
spinning = true;
spinButton.disabled = true;
const spinDuration = 3000; // 旋转持续时间(毫秒)
const startTime = Date.now();
const startAngle = currentAngle;
const targetAngle = startAngle + 10 * Math.PI + Math.random() * 2 * Math.PI; // 随机旋转角度
function animate() {
const elapsed = Date.now() - startTime;
if (elapsed < spinDuration) {
const progress = easeOut(elapsed / spinDuration);
currentAngle = startAngle + progress * (targetAngle - startAngle);
drawWheel();
requestAnimationFrame(animate);
} else {
currentAngle = targetAngle % (2 * Math.PI);
drawWheel();
spinning = false;
spinButton.disabled = false;
const prizeIndex = Math.floor(((2 * Math.PI - currentAngle) % (2 * Math.PI)) / (2 * Math.PI / prizes.length));
alert('恭喜获得: ' + prizes[prizeIndex]);
}
}
function easeOut(t) {
return 1 - Math.pow(1 - t, 3);
}
animate();
}
// 绑定按钮事件
spinButton.addEventListener('click', spinWheel);
// 初始绘制
drawWheel();
});
实现细节
- 转盘绘制:使用Canvas API绘制转盘,每个扇形区域代表一个奖品。
- 旋转动画:通过
requestAnimationFrame实现平滑的旋转动画,使用缓动函数使旋转更自然。 - 奖品判定:根据旋转停止时的角度计算对应的奖品索引。
优化建议
- 响应式设计:添加媒体查询使转盘在不同屏幕尺寸下都能正常显示。
- 奖品配置:将奖品和颜色配置为可动态修改的数组,方便扩展。
- 性能优化:在旋转过程中减少不必要的重绘操作。
以上代码实现了一个基础的转盘抽奖功能,可根据实际需求进行调整和扩展。







