萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML5 Canvas 實作刮刮卡效果:完整原理與程式碼

利用 Canvas 的 `globalCompositeOperation = 'destination-out'` 特性,輕鬆實現刮刮卡刮開效果。支援滑鼠與觸控雙模式。

核心原理

  1. Canvas 繪製背景獎品圖
  2. 上層填滿灰色遮罩(或指定圖片)
  3. 設定 `globalCompositeOperation = 'destination-out'`
  4. 滑鼠/手指移動時繪製透明圓形,「刮除」遮罩露出底圖

完整實作程式碼

<canvas id="scratchCard"></canvas>
<style>
  #scratchCard { position: absolute; cursor: crosshair; }
  body { user-select: none; -webkit-user-select: none; }
</style>

<script>
const canvas = document.getElementById('scratchCard');
const ctx = canvas.getContext('2d');

// 1. 隨機選擇背景圖
const bgImages = ['prize1.jpg', 'prize2.jpg'];
const bgImg = new Image();
bgImg.src = bgImages[Math.floor(Math.random() * bgImages.length)];

bgImg.onload = () => {
  const w = canvas.width = bgImg.width;
  const h = canvas.height = bgImg.height;
  const offsetX = canvas.offsetLeft, offsetY = canvas.offsetTop;
  let isDrawing = false;

  // 繪製背景獎品
  ctx.drawImage(bgImg, 0, 0);
  // 繪製灰色遮罩層
  ctx.fillStyle = '#ccc';
  ctx.fillRect(0, 0, w, h);

  // 關鍵:設定合成模式為「刮除」
  ctx.globalCompositeOperation = 'destination-out';
  ctx.lineWidth = 30; // 刮刷寬度
  ctx.lineCap = 'round';
  ctx.strokeStyle = 'rgba(0,0,0,1)'; // 任意不透明色即可

  // 事件綁定
  ['mousedown','touchstart'].forEach(evt => canvas.addEventListener(evt, start));
  ['mousemove','touchmove'].forEach(evt => canvas.addEventListener(evt, draw));
  ['mouseup','mouseout','touchend'].forEach(evt => canvas.addEventListener(evt, stop));

  function getPos(e) {
    e.preventDefault();
    const clientX = e.clientX || e.touches[0].clientX;
    const clientY = e.clientY || e.touches[0].clientY;
    return {
      x: clientX - offsetX + (document.body.scrollLeft || 0),
      y: clientY - offsetY + (document.body.scrollTop || 0)
    };
  }

  function start(e) { isDrawing = true; draw(e); }
  function stop() { isDrawing = false; ctx.beginPath(); }
  function draw(e) {
    if (!isDrawing) return;
    const pos = getPos(e);
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
    ctx.beginPath();
    ctx.moveTo(pos.x, pos.y);
  }
};
</script>

進階擴充

  • 刮開比例檢測:定期採樣像素透明度,超過 50% 自動全清除並觸發中獎邏輯。
  • 自訂遮罩圖片:用 `drawImage` 繪製品牌 Logo 遮罩,替代純色填滿。
  • 重置功能:重新繪製遮罩層即可重玩。
  • 後端整合:獎品資訊、中獎機率由後端 API 提供,前端僅負責呈現。

效能提示

  • Canvas 尺寸建議 ≤ 600px,避免高解析度裝置記憶體壓力。
  • 使用 `requestAnimationFrame` 節流繪製回呼。
  • 觸控事件加上 `{passive: false}` 確保 `preventDefault()` 生效。

此技術廣泛應用於行銷活動、優惠券發放、遊戲抽獎,體驗直觀且開發成本低。

copyright © 萬盛學電腦網 all rights reserved