How to Build an HTML5 Canvas Scratch-Off Card with CSS & JavaScript
To build an HTML5 canvas scratch-off reveal card, layer a transparent <canvas> element directly above a hidden prize or promo code container. Paint the canvas with an opaque metallic foil or color fill, and when pointer or touch movement is detected, set ctx.globalCompositeOperation = "destination-out" and draw circular brush strokes at the cursor coordinates. Calculate the percentage of cleared pixels with getImageData(), and automatically fade out the entire canvas once an 80% reveal threshold is reached.
Step 1: Stacking the Secret Prize Layer & Canvas Overlay
Place the secret reward (HTML text, image, or coupon code) inside a relative container. Position an HTML5 <canvas> element directly on top with position: absolute; inset: 0; to completely conceal the prize beneath.
<div class="scratch-card-wrapper" style="position: relative; width: 320px; height: 160px;">
<!-- Underneath: Prize Content -->
<div class="prize-content">
<h3>CONGRATULATIONS!</h3>
<p class="promo-code">SAVE-25-NOW</p>
</div>
<!-- Top: Canvas Scratch Layer -->
<canvas id="scratchCanvas" width="320" height="160" style="position: absolute; inset: 0; cursor: crosshair;"></canvas>
</div>
Step 2: Painting the Opaque Metallic Foil Surface
In your JavaScript initialization function, render an opaque metallic gradient or patterned texture across the entire canvas context so that the underlying HTML content remains 100% invisible until scratched.
const canvas = document.getElementById('scratchCanvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
function initFoil() {
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#94a3b8');
gradient.addColorStop(0.5, '#cbd5e1');
gradient.addColorStop(1, '#64748b');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Optional surface instructions
ctx.font = 'bold 16px sans-serif';
ctx.fillStyle = '#1e293b';
ctx.textAlign = 'center';
ctx.fillText('🪙 SCRATCH WITH COIN', canvas.width / 2, canvas.height / 2 + 6);
}
Step 3: The Erasing Secret: globalCompositeOperation = "destination-out"
The critical magic of canvas scratch cards is ctx.globalCompositeOperation = "destination-out". Any shape drawn in this composite mode punches a transparent hole through the existing canvas pixels rather than adding paint.
let isScratching = false;
function scratch(x, y) {
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, 18, 0, Math.PI * 2); // 18px radius coin brush
ctx.fill();
checkRevealThreshold();
}
canvas.addEventListener('pointerdown', (e) => { isScratching = true; scratch(e.offsetX, e.offsetY); });
window.addEventListener('pointerup', () => { isScratching = false; });
canvas.addEventListener('pointermove', (e) => {
if (isScratching) scratch(e.offsetX, e.offsetY);
});
Step 4: Calculating Reveal Thresholds with getImageData()
Periodically sample alpha channel values across the canvas. Count the percentage of pixels where alpha equals zero. Once the user has scratched away 75% or 80%, smoothly animate the canvas opacity to zero to reveal the full prize automatically.
function checkRevealThreshold() {
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const totalPixels = imgData.data.length / 4;
let clearedCount = 0;
// Sample every 4th pixel for performance
for (let i = 3; i < imgData.data.length; i += 16) {
if (imgData.data[i] === 0) clearedCount++;
}
const percent = (clearedCount / (totalPixels / 4)) * 100;
if (percent > 75) {
canvas.style.transition = 'opacity 0.6s ease';
canvas.style.opacity = '0';
canvas.style.pointerEvents = 'none';
}
}
Next-Level Addons: Elevating Your Implementation
Take this technique further by combining it with complementary design token studios and animation tools:
When building high-performance UI animations or particle systems, my golden rule is: never calculate layout triggers (like getBoundingClientRect() or offsetHeight) inside animation loops. Read measurements once upfront and use CSS transforms or Canvas for buttery 60fps.
Frequently Asked Questions
Practical answers to common implementation questions, browser quirks, and performance tips.
How does globalCompositeOperation = "destination-out" work in canvas?
The `destination-out` compositing mode retains only the existing pixels that do *not* overlap with the new shape being drawn. In practice, drawing a circle with destination-out erases whatever pixels were underneath, acting as an eraser.
Why can checking getImageData() cause performance lag on mobile devices?
Reading pixel data from the GPU into CPU memory via `ctx.getImageData()` can be costly. To keep frame rates at 60fps, sample pixels at stepped intervals (e.g. every 8th or 16th pixel) and throttle the check using a timer or `requestAnimationFrame`.
How do I ensure touch events work seamlessly on mobile phones without scrolling the page?
Apply the CSS property `touch-action: none` to the `
Can users cheat and inspect the prize code using browser DevTools?
Yes. If the coupon code is rendered directly in the HTML DOM beneath the canvas, any user can inspect the element. To prevent cheating, keep the prize on the server and fetch the code via API only after the threshold callback fires.
What is an accessible fallback for users with motor impairments who cannot rub the screen?
Always include a visible, accessible HTML `