canvas实现一个抽奖轮盘
时间: 2023-08-12 19:36:23 浏览: 180
好的,以下是一个简单的抽奖轮盘实现,使用HTML5 Canvas来绘制:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>抽奖轮盘</title>
<meta charset="UTF-8">
<style>
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500"></canvas>
<button onclick="start()">开始</button>
</body>
</html>
```
JavaScript:
```javascript
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var angle = 0;
var rotateAngle = 0;
var prizeArr = ["一等奖", "二等奖", "三等奖", "再接再厉", "谢谢参与"];
var colorArr = ["#FFB6C1", "#FF69B4", "#FF1493", "#DB7093", "#C71585"];
//绘制背景
function drawBg(){
ctx.save();
ctx.translate(250, 250);
var colors = colorArr;
var startAngle = 0;
var endAngle = 0;
for(var i = 0; i < 5; i++){
startAngle = endAngle;
endAngle = startAngle + Math.PI * 2 / 5;
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(0, 0, 200, startAngle, endAngle);
ctx.closePath();
ctx.fillStyle = colors[i];
ctx.fill();
}
ctx.restore();
}
//绘制文本
function drawText(){
ctx.save();
ctx.translate(250, 250);
var text = prizeArr;
var angle = Math.PI / 5;
ctx.font = "bold 20px Arial";
ctx.fillStyle = "#fff";
for(var i = 0; i < 5; i++){
ctx.beginPath();
ctx.rotate(angle);
ctx.fillText(text[i], -50, -170);
ctx.closePath();
angle += Math.PI * 2 / 5;
}
ctx.restore();
}
//绘制指针
function drawPointer(){
ctx.save();
ctx.translate(250, 250);
ctx.rotate(rotateAngle);
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(0, -150);
ctx.strokeStyle = "#FF0000";
ctx.lineWidth = 5;
ctx.stroke();
ctx.closePath();
ctx.restore();
}
//开始旋转
function start(){
if(rotateAngle == 0){
angle = Math.floor(Math.random() * 5) * (Math.PI / 5);
rotateAngle = angle + Math.PI * 2 * 6;
}
var timer = setInterval(function(){
drawBg();
drawText();
drawPointer();
rotateAngle -= Math.PI / 180 * 5;
if(rotateAngle <= angle){
clearInterval(timer);
alert(prizeArr[Math.floor((angle + Math.PI / 5 / 2) / (Math.PI / 5) % 5)]);
rotateAngle = 0;
}
}, 30);
}
drawBg();
drawText();
```
该代码实现了一个简单的抽奖轮盘,点击“开始”按钮时,轮盘将开始旋转,最终停在一个随机的奖项上。在这个例子中,奖项分别为“一等奖”、“二等奖”、“三等奖”、“再接再厉”和“谢谢参与”,奖项的背景颜色为不同的颜色。
阅读全文