Scratch Card Effect
Home
Snippets
Scratch Card Effect
HTML
CSS
JS
<div class="scratch-container"> <div class="hidden-message">You Won a Gift!</div> <canvas id="scratchCanvas"></canvas> </div>
body { height: 100vh; margin: 0; display: flex; justify-content: center; align-items: center; background: #f4f4f9; font-family: Arial, sans-serif; } .scratch-container { position: relative; width: 300px; height: 200px; border-radius: 12px; overflow: hidden; box-shadow: 0 8px 16px rgba(0,0,0,0.2); } .hidden-message { position: absolute; inset: 0; display: flex; justify-content: center; align-items: center; font-size: 1.5rem; font-weight: bold; color: white; background: linear-gradient(135deg, #28a745, #218838); } canvas { position: absolute; inset: 0; cursor: crosshair; }
const canvas = document.getElementById("scratchCanvas"); const ctx = canvas.getContext("2d"); canvas.width = 300; canvas.height = 200; ctx.fillStyle = "#c0c0c0"; ctx.fillRect(0, 0, canvas.width, canvas.height); let isDrawing = false; function getPosition(e) { const rect = canvas.getBoundingClientRect(); return { x: (e.clientX || e.touches[0].clientX) - rect.left, y: (e.clientY || e.touches[0].clientY) - rect.top }; } function scratch(e) { if (!isDrawing) return; const pos = getPosition(e); ctx.globalCompositeOperation = "destination-out"; ctx.beginPath(); ctx.arc(pos.x, pos.y, 20, 0, Math.PI * 2); ctx.fill(); } canvas.addEventListener("mousedown", () => (isDrawing = true)); canvas.addEventListener("mouseup", () => (isDrawing = false)); canvas.addEventListener("mousemove", scratch); canvas.addEventListener("touchstart", () => (isDrawing = true)); canvas.addEventListener("touchend", () => (isDrawing = false)); canvas.addEventListener("touchmove", scratch);
Ad #1
Ad #2
Scroll to Top