利用 Canvas 的 `globalCompositeOperation = 'destination-out'` 特性,輕鬆實現刮刮卡刮開效果。支援滑鼠與觸控雙模式。
<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>
此技術廣泛應用於行銷活動、優惠券發放、遊戲抽獎,體驗直觀且開發成本低。