html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>随机转盘游戏</title>
<style>
canvas {
border: 1px solid black;
}
#rotateBtn {
margin-top: 20px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<button id="refreshBtn">刷新</button>
<button id="rotateBtn">开始</button>
<script src="game.js"></script>
</body>
</html>
javascript
class Game {
constructor() {
this.canvas = document.getElementById("myCanvas");
this.context = this.canvas.getContext("2d");
this.sectors = [
"奖品1",
"奖品2",
"奖品3",
"奖品4",
"奖品5",
"奖品6",
"奖品7",
"奖品8"
];
this.sectorColors = [
"#FF0000",
"#FF7F00",
"#FFFF00",
"#00FF00",
"#00FFFF",
"#0000FF",
"#8B00FF",
"#FF00FF"
];
this.rotateSpeed = 0;
this.rotateAngle = 0;
this.rotateDirection = 1;
this.drawSectors();
document.getElementById("refreshBtn").addEventListener("click", () => {
this.drawSectors();
});
document.getElementById("rotateBtn").addEventListener("click", () => {
if (this.rotateSpeed === 0) {
this.rotateSpeed = 10;
this.startRotation();
} else {
this.stopRotation();
}
});
}
drawSectors() {
const numSectors = this.sectors.length;
const sectorSize = (2 * Math.PI) / numSectors;
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
for (let i = 0; i < numSectors; i++) {
const startAngle = i * sectorSize;
const endAngle = (i + 1) * sectorSize;
this.context.beginPath();
this.context.moveTo(this.canvas.width / 2, this.canvas.height / 2);
this.context.arc(
this.canvas.width / 2,
this.canvas.height / 2,
this.canvas.width / 2,
startAngle,
endAngle
);
this.context.closePath();
this.context.fillStyle = this.sectorColors[i];
this.context.fill();
// 绘制文本
this.context.save();
this.context.translate(
this.canvas.width / 2,
this.canvas.height / 2
);
this.context.rotate(startAngle + sectorSize / 2);
this.context.fillStyle = "white";
this.context.font = "bold 20px Arial";
this.context.fillText(
this.sectors[i],
this.canvas.width / 3,
10
);
this.context.restore();
}
}
startRotation() {
const rotateInterval = setInterval(() => {
this.rotateAngle += this.rotateDirection * this.rotateSpeed;
if (this.rotateSpeed >= 0.1) {
this.rotateSpeed -= 0.1;
} else {
this.rotateSpeed = 0;
clearInterval(rotateInterval);
}
this.drawSectors();
this.rotateWheel();
}, 1000 / 60);
}
stopRotation() {
this.rotateSpeed = 0;
}
rotateWheel() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.save();
this.context.translate(
this.canvas.width / 2,
this.canvas.height / 2
);
this.context.rotate(this.rotateAngle);
this.context.translate(
-this.canvas.width / 2,
-this.canvas.height / 2
);
this.drawSectors();
this.context.restore();
}
}
const game = new Game();
你可以将HTML代码与JS代码放在同一个文件中,然后用浏览器打开该文件,即可运行随机转盘游戏。通过点击“刷新”按钮,可以随机更新扇形分布;点击“开始”按钮,可以开始旋转,再次点击可以暂停旋转。