html页面转盘如何实现,html+js实现大转盘例子
时间: 2024-01-09 08:04:25 浏览: 31
实现一个 HTML 页面转盘可以使用 HTML 和 JavaScript 来完成。以下是一个简单的例子:
HTML 代码:
```html
<div id="container">
<canvas id="canvas" width="300" height="300"></canvas>
<button id="spin">Spin</button>
</div>
```
JavaScript 代码:
```js
// 获取画布和按钮元素
const canvas = document.getElementById("canvas");
const spinBtn = document.getElementById("spin");
// 获取画布上下文
const ctx = canvas.getContext("2d");
// 绘制转盘
const colors = ["#F44336", "#E91E63", "#9C27B0", "#673AB7", "#3F51B5", "#2196F3", "#03A9F4", "#00BCD4", "#009688", "#4CAF50", "#8BC34A", "#CDDC39", "#FFEB3B", "#FFC107", "#FF9800", "#FF5722"];
const slices = 16;
const sliceAngle = Math.PI * 2 / slices;
ctx.lineWidth = 2;
ctx.font = "bold 14px Arial";
for (let i = 0; i < slices; i++) {
const angle = i * sliceAngle;
ctx.fillStyle = colors[i % colors.length];
ctx.beginPath();
ctx.arc(150, 150, 100, angle, angle + sliceAngle);
ctx.lineTo(150, 150);
ctx.closePath();
ctx.fill();
ctx.stroke();
const text = `Prize ${i + 1}`;
ctx.save();
ctx.translate(150, 150);
ctx.rotate(angle + sliceAngle / 2);
ctx.textAlign = "right";
ctx.fillStyle = "#fff";
ctx.fillText(text, -5, 0);
ctx.restore();
}
// 定义转盘旋转函数
function spin() {
const spinAngleStart = 10;
const spinTime = 0;
const spinTimeTotal = Math.random() * 3 + 4 * 1000;
const spinAngleTotal = Math.floor(Math.random() * 360);
const spinAngle = spinAngleTotal * Math.PI / 180;
rotateWheel(spinAngleStart, spinTime, spinTimeTotal, spinAngleTotal);
}
// 定义转盘旋转动画函数
function rotateWheel(spinAngleStart, spinTime, spinTimeTotal, spinAngleTotal) {
spinTime += 30;
if (spinTime >= spinTimeTotal) {
stopRotateWheel(spinAngleStart, spinAngleTotal);
return;
}
const spinAngle = spinAngleStart - easeOut(spinTime, 0, spinAngleStart, spinTimeTotal);
ctx.clearRect(0, 0, 300, 300);
ctx.save();
ctx.translate(150, 150);
ctx.rotate(spinAngle);
for (let i = 0; i < slices; i++) {
const angle = i * sliceAngle;
ctx.fillStyle = colors[i % colors.length];
ctx.beginPath();
ctx.arc(0, 0, 100, angle, angle + sliceAngle);
ctx.lineTo(0, 0);
ctx.closePath();
ctx.fill();
ctx.stroke();
const text = `Prize ${i + 1}`;
ctx.save();
ctx.rotate(angle + sliceAngle / 2);
ctx.textAlign = "right";
ctx.fillStyle = "#fff";
ctx.fillText(text, -5, 0);
ctx.restore();
}
ctx.restore();
requestAnimationFrame(() => rotateWheel(spinAngleStart, spinTime, spinTimeTotal, spinAngleTotal));
}
// 定义旋转停止函数
function stopRotateWheel(spinAngleStart, spinAngleTotal) {
const spinAngle = spinAngleStart - spinAngleTotal * Math.PI / 180;
const prize = slices - 1 - Math.floor((spinAngle % (Math.PI * 2)) / sliceAngle);
alert(`You won ${prize + 1}`);
}
// 定义缓动函数
function easeOut(t, b, c, d) {
const ts = (t /= d) * t;
const tc = ts * t;
return b + c * (tc + -3 * ts + 3 * t);
}
// 绑定按钮点击事件
spinBtn.addEventListener("click", spin);
```
这段代码将创建一个包含转盘和一个按钮的 HTML 页面。当用户点击按钮时,转盘将旋转并最终停止在一个随机位置。转盘的每个扇区都包含一个奖品标签。