html5转盘抽奖代码
时间: 2023-09-24 16:13:30 浏览: 149
我了解您的问题。以下是一个简单的HTML5转盘抽奖代码的示例:
HTML代码:
```
<div>
<canvas id="canvas" width="400" height="400"></canvas>
<button onclick="start()">开始抽奖</button>
</div>
```
JavaScript代码:
```
var colors = ["#FC4349", "#5BC0EB", "#E55934", "#FDE74C", "#9BC53D", "#46B29D"];
var prizes = ["奖品1", "奖品2", "奖品3", "奖品4", "奖品5", "奖品6"];
var startAngle = 0;
var arcs = [];
var spinTimeout = null;
var spinArcStart = 10;
var spinTime = 0;
var spinTotal = 0;
var ctx;
function draw() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var outsideRadius = 180;
var insideRadius = 110;
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 400, 400);
// 绘制转盘扇形和文字
for (var i = 0; i < 6; i++) {
var angle = startAngle + i * Math.PI / 3;
ctx.fillStyle = colors[i];
ctx.beginPath();
ctx.arc(200, 200, outsideRadius, angle, angle + Math.PI / 3, false);
ctx.arc(200, 200, insideRadius, angle + Math.PI / 3, angle, true);
ctx.fill();
ctx.save();
ctx.shadowOffsetX = -1;
ctx.shadowOffsetY = -1;
ctx.shadowBlur = 0;
ctx.shadowColor = "rgb(220,220,220)";
ctx.fillStyle = "white";
ctx.translate(200 + Math.cos(angle + Math.PI / 6) * 140,
200 + Math.sin(angle + Math.PI / 6) * 140);
ctx.rotate(angle + Math.PI / 6);
var text = prizes[i];
ctx.fillText(text, -ctx.measureText(text).width / 2, 0);
ctx.restore();
}
// 绘制转盘中心的圆形和文字
ctx.beginPath();
ctx.arc(200, 200, 60, 0, 2 * Math.PI, false);
ctx.fillStyle = "white";
ctx.fill();
ctx.lineWidth = 2;
ctx.strokeStyle = "#444";
ctx.stroke();
ctx.fillStyle = "#000";
ctx.font = "bold 36px Arial";
ctx.fillText("抽奖", 165, 210);
ctx.fillRect(180, 190, 40, 10);
}
}
function spin() {
spinTotal += spinTime;
if (spinTotal >= spinTimeout) {
stopRotateWheel();
return;
}
var spinAngle = spinAngleCalc();
startAngle += (spinAngle * Math.PI / 180);
draw();
spinTime += 20;
setTimeout('spin()', 20);
}
function spinAngleCalc() {
var i = Math.floor(Math.random() * (arcs.length));
return arcs[i] * 360 / 6;
}
function stopRotateWheel() {
clearTimeout(spinTimeout);
var degrees = startAngle * 180 / Math.PI + 90;
var arcd = arcDeg(degrees);
var index = Math.floor((360 - arcd) / (360 / 6));
ctx.save();
ctx.font = 'bold 48px Arial';
var text = prizes[index]
ctx.fillText(text, 200 - ctx.measureText(text).width / 2, 480);
ctx.restore();
}
function arcDeg(degrees) {
return (degrees % 360) * (Math.PI / 180);
}
function start() {
startAngle = 0;
spinTotal = 0;
spinTime = 0;
spinTimeout = Math.random() * 2000 + 1000;
var prize = Math.floor((Math.random() * prizes.length));
arcs = [];
for (var i = 1; i < 7; i++) {
arcs.push(i * 60 - spinArcStart - 60 / (prizes.length - 1) * prize);
}
spin();
}
```
请注意,此代码仅用于演示目的,可能需要进行进一步修改以适应您的应用程序要求。
阅读全文