最近项目加了个大转盘和刮一刮抽奖的需求,趁着最近不是很忙,研究了一下大转盘抽奖的实现。
下面直接上代码:
<!DOCTYPE html>
<html>
<title>大转盘</title>
<head></head>
<style>
.pen {
width: 500px;
height: 500px;
border-radius: 100%;
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.point {
width: 20px;
height: 20px;
background: #000;
border-radius: 50%;
position: absolute;
z-index: 4;
}
.line {
height: 100px;
position: absolute;
width: 10px;
background: red;
z-index: 5;
bottom: 250px;
}
.box {
width: 500px;
height: 500px;
border-radius: 100%;
background: #ddd;
position: absolute;
z-index: 3;
}
#canvasBox {
position: relative;
}
.rotateClass {
animation: rotate 10s ease-in-out 0s 1 normal forwards;
}
#canvasBox canvas {
position: absolute;
}
</style>
<body>
<div class="pen">
<div class="box" id='canvasBox'></div>
<div class="point"></div>
<div class="line"> </div>
</div>
<script>
let imgList=['img1','img2','']
let n = 10 //转盘分格数
// n 转盘分为n块
function init(n) {
// 画n个圆弧
for (let i = 0; i < n; i++) {
let canvas = document.createElement('canvas')
canvas.setAttribute('id', 'parentCanvas' + i)
canvas.width = 500
canvas.height = 500
canvas.style.borderRadius = '50%'
canvas.style.transform = `rotateZ(${360*i/n}deg)`
let canvasBox = document.querySelector('#canvasBox')
canvasBox.appendChild(canvas)
let ctx = canvas.getContext('2d')
ctx.translate(250, 250)
ctx.beginPath()
ctx.moveTo(0, 0)
// 开始
let startDeg=270-360/n/2
// 结束
let endDeg=270+360/n/2
ctx.arc(0, 0, 250,startDeg/360 * 2 * Math.PI, endDeg / 360 * 2 * Math.PI, false)
ctx.lineTo(0, 0)
ctx.strokeStyle = '#999'
ctx.stroke();
if(imgList[i%imgList.length]){
let img=document.createElement('img')
img.src=imgList[i%imgList.length]
img.onload = function(){
ctx.drawImage(img,-30,-185,70,70)
}
ctx.font = "30px Verdana";
ctx.textAlign = 'center'
ctx.strokeText('canvas' + i, 0, -225)
}else{
ctx.font = "30px Verdana";
ctx.textAlign = 'center'
ctx.strokeText('谢谢参与' , 0, -125)
}
}
}
// 旋转
// n 转盘跨数 count:中奖的次序
function rotate(n,count = 2) {
// 每个圆弧的弧度
let deg = 360/n
let animation = `@keyframes rotate {
form{
transform: rotateZ(0deg);
}
to{
transform: rotateZ(${7200-deg*count}deg);
}
}`
var sheet = document.styleSheets[0]
sheet.insertRule(animation, 0)
canvasBox.classList.add('rotateClass')
}
init(n)
rotate(n,8)
</script>
</body>
</html>
其实上面的代码实现还有很大的改进的空间(暂时还没有时间改造),有什么不对的地方望各位大佬,也期待更多大佬分享自己的实现方法和思路。