实现思路完全属于自己想的,所以可能和其他人的实现不一样,也不能保证是最佳的实现方案。
不喜勿喷
1、使用canvas绘制转盘,arc()绘制扇形,drawImage()绘制奖品图片
2、利用 CSS3中的 transform :rotate 实现旋转
绘制转盘方法:
(具体数值要根据画布大小调整,这里我的画布大小是401px)
// 绘制转盘
function drawBg() {
var one_angle = Math.PI * 2 / prize.length;
var start_angle = -Math.PI / 2 - one_angle / 2
ctx.translate(200.5, 200.5);
ctx.arc(0, 0, 200, 0, Math.PI * 2, false);
ctx.stroke()
//绘制扇形
prize.forEach((item, i) => {
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.arc(0, 0, 200, start_angle + one_angle * i, start_angle + one_angle * (i + 1), false);
if (i % 2 == 0) {
ctx.fillStyle = "rgba(230,186,127,1)"
} else {
ctx.fillStyle = "rgba(210,156,97,1)"
}
ctx.fill()
// 绘制奖品
var newImg = new Image()
newImg.src = prize[i].img
newImg.onload = function() {
ctx.rotate(one_angle * i);
ctx.fillStyle = "rgba(0,0,0,1)"
//ctx.font = '16px Microsoft YaHei';
ctx.drawImage(newImg, 0, 0, 232, 200, -27, -190, 54, 54)
//ctx.fillText(prize[i].name, -ctx.measureText(prize[i].name).width / 2, -112)
ctx.rotate(-one_angle * i);
}
ctx.save();
})
}
抽奖方法:
function luckyDraw(activeIndex) {
// 旋转几圈
var turnNum = 4
// 当前选中下标
var currentIndex = prize.length - (window.currentRotateAngle % 360 / (360 / prize.length))
var turnIndex = 0
if (activeIndex > currentIndex) {
turnIndex = activeIndex - currentIndex
} else {
turnIndex = prize.length - (currentIndex - activeIndex)
}
var turnAngle = (turnNum + 1) * 360 - turnIndex * (360 / prize.length)
canvasDom.style.transform = "rotate(" + (turnAngle + window.currentRotateAngle) + "deg)";
window.currentRotateAngle = turnAngle + window.currentRotateAngle
// 显示抽奖结果
// setTimeout()
}
1、通过当前奖品显示个数计算宫格多少列,每个方块大小
2、计算没方块的xy并设置样式
3、点击抽奖时轮流添加选中样式
初始化容器内容
function initContent() {
if (prize.length % 4 != 0) {
alert("奖品个数需为4的倍数")
return
}
let par_row_num = null;
let par_col_num = null;
for (let i = 0; i < prize.length; i++) {
var row_num = null;
var col_num = null;
var x = 0;
var y = 0;
if (par_row_num === null) {
row_num = 0;
col_num = 0;
} else if (par_row_num == 0 && par_col_num < (max_col_num - 1)) {
row_num = par_row_num;
col_num = par_col_num + 1;
} else if (par_col_num == (max_col_num - 1) && par_row_num < (max_col_num - 1)) {
row_num = par_row_num + 1;
col_num = par_col_num;
} else if (par_row_num == (max_col_num - 1) && par_col_num > 0) {
row_num = par_row_num;
col_num = par_col_num - 1;
} else if (par_col_num == 0 && par_row_num > 0) {
row_num = par_row_num - 1;
col_num = par_col_num;
}
x = col_num * (prizeBoxWidth + prizeBoxMargin * 2) + prizeBoxMargin
y = row_num * (prizeBoxWidth + prizeBoxMargin * 2) + prizeBoxMargin
// 给元素设置样式 或 通过html字符串拼接容器内容
// ......
par_row_num = row_num
par_col_num = col_num
}
}
抽奖方法就没什么好解说的,给元素添加选中样式而已