html5

刮刮乐

(function () {
  let canvas = document.getElementById('canvas');
  let ctx = canvas.getContext('2d');
  // 绘制涂层
  ctx.beginPath();
  ctx.fillStyle = 'red';
  ctx.fillRect(0, 0, 100, 50);
  ctx.fillStyle = 'black';
  ctx.font = '18px "宋体"';
  ctx.fillText('刮一刮', canvas.width / 2 - 34, canvas.height / 2);
  // 给 canvas 添加监听鼠标移动事件
  canvas.addEventListener('mousemove', m => {
    if (m.which === 1 && m.button === 0) {
      const x = m.clientX - canvas.offsetLeft;
      const y = m.clientY - canvas.offsetTop;
      ctx.globalCompositeOperation = 'destination-out';
      ctx.beginPath();
      // 清除以鼠标位置为圆心,半径为10px的圆的范围
      ctx.arc(x, y, 10, 0, 2 * Math.PI);
      ctx.fill();
    }
  });
})();
上次更新: