返回

DIY幸运抽奖抽取一份预知未来的安慰剂

前端

俗话说的好,抽奖是不可能抽中的,只有攒攒矿石安慰一下自己。要是有一台可以预知自己奖品的大转盘,那还不是随便转?

闲来无聊的我,用canvas制作了一个“幸运”抽奖的转盘,给自己一波预知未来的鼓励,界面和juejin上的基本一样,用来自娱自乐。

好的,那么接下来我们就开始!

首先,你需要创建一个<canvas>元素,并将其添加到你的HTML文档中。<canvas>元素是一个用于在网页上绘制图形的元素。

<canvas id="canvas" width="500" height="500"></canvas>

接下来,你需要创建一个JavaScript文件,并将其链接到你的HTML文档。JavaScript文件将包含用于创建和绘制转盘的代码。

// 获取canvas元素
const canvas = document.getElementById('canvas');

// 获取canvas的上下文
const ctx = canvas.getContext('2d');

// 设置转盘的半径
const radius = 200;

// 设置转盘的中心点
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;

// 创建转盘的各个扇形
const sectors = [
  {
    name: '奖品1',
    color: '#ff0000',
    startAngle: 0,
    endAngle: Math.PI * 2 / 8
  },
  {
    name: '奖品2',
    color: '#00ff00',
    startAngle: Math.PI * 2 / 8,
    endAngle: Math.PI * 2 / 4
  },
  {
    name: '奖品3',
    color: '#0000ff',
    startAngle: Math.PI * 2 / 4,
    endAngle: Math.PI * 2 / 2
  },
  {
    name: '奖品4',
    color: '#ffff00',
    startAngle: Math.PI * 2 / 2,
    endAngle: Math.PI * 2 * 3 / 4
  },
  {
    name: '奖品5',
    color: '#ff00ff',
    startAngle: Math.PI * 2 * 3 / 4,
    endAngle: Math.PI * 2
  },
  {
    name: '谢谢参与',
    color: '#000000',
    startAngle: Math.PI * 2,
    endAngle: Math.PI * 2 * 2
  }
];

// 绘制转盘的背景
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, canvas.width, canvas.height);

// 绘制转盘的各个扇形
for (let i = 0; i < sectors.length; i++) {
  const sector = sectors[i];

  ctx.fillStyle = sector.color;
  ctx.beginPath();
  ctx.moveTo(centerX, centerY);
  ctx.arc(centerX, centerY, radius, sector.startAngle, sector.endAngle);
  ctx.lineTo(centerX, centerY);
  ctx.fill();
}

// 绘制转盘的指针
ctx.fillStyle = '#000000';
ctx.beginPath();
ctx.moveTo(centerX, centerY);
ctx.lineTo(centerX + radius / 2, centerY);
ctx.stroke();

// 添加转盘的事件监听器
canvas.addEventListener('click', (e) => {
  // 计算鼠标点击的位置
  const x = e.clientX - canvas.getBoundingClientRect().left;
  const y = e.clientY - canvas.getBoundingClientRect().top;

  // 计算鼠标点击的角度
  const angle = Math.atan2(y - centerY, x - centerX);

  // 查找鼠标点击的扇形
  let sector = null;
  for (let i = 0; i < sectors.length; i++) {
    const s = sectors[i];
    if (angle >= s.startAngle && angle < s.endAngle) {
      sector = s;
      break;
    }
  }

  // 显示中奖结果
  alert(`恭喜你,你中了${sector.name}!`);
});

保存JavaScript文件,并将它链接到你的HTML文档中。然后,你就可以在浏览器中打开你的HTML文档,并点击转盘来抽奖了。

当然,你也可以根据自己的需要来修改转盘的界面和奖品。比如,你可以添加更多的奖品,或者你可以改变转盘的配色方案。