html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Spin Game</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f0f0f0;
}
.ring {
width: 460px;
height: 460px;
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
background-color:deepskyblue;
position: relative;
}
#gameCanvas {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="ring">
<canvas id="gameCanvas"></canvas>
</div>
<button onclick="startSpin()">开始旋转</button>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const radius = 200; // 转盘半径
const centerX = canvas.width / 2; // 转盘中心点的 x 坐标
const centerY = canvas.height / 2; // 转盘中心点的 y 坐标
const sectorColors = ['#FF5733', '#FFC300', '#4CAF50', '#3498db', '#9B59B6', '#E74C3C', '#F39C12', '#2C3E50']; // 扇形的颜色
const sectorPrizes = ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6', '奖品7', '奖品8']; // 奖项
function drawWheel() {
const numberOfSectors = sectorPrizes.length;
const sectorAngle = (2 * Math.PI) / numberOfSectors;
for (let i = 0; i < numberOfSectors; i++) {
const startAngle = i * sectorAngle;
const endAngle = (i + 1) * sectorAngle;
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.arc(centerX, centerY, radius, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = sectorColors[i % sectorColors.length];
ctx.fill();
const text = sectorPrizes[i];
const textAngle = startAngle + sectorAngle / 2;
const textX = centerX + Math.cos(textAngle) * radius * 0.5;
const textY = centerY + Math.sin(textAngle) * radius * 0.5;
ctx.save();
ctx.translate(textX, textY);
ctx.rotate(textAngle + Math.PI / 2);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '16px Arial';
ctx.fillStyle = '#fff';
ctx.fillText(text, 0, 0);
ctx.restore();
}
}
function startSpin() {
const numberOfSpins = 2; // 旋转圈数
const targetSector = Math.floor(Math.random() * sectorPrizes.length); // 随机选择一个奖项作为目标扇形
const totalAngle = targetSector * (2 * Math.PI / sectorPrizes.length) + (2 * Math.PI) * numberOfSpins;
let currentAngle = 0;
const spinSpeed = 0.08; // 旋转速度
function spinAnimation() {
currentAngle += spinSpeed;
if (currentAngle >= totalAngle) {
// 到达目标角度,停止旋转
return;
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(currentAngle);
ctx.translate(-centerX, -centerY);
drawWheel();
ctx.restore();
requestAnimationFrame(spinAnimation);
}
spinAnimation();
}
drawWheel(); // 初始绘制转盘
</script>
</body>
</html>