About this snippet

Add a fun interactive element to your site with this scratch-off card. We use HTML5 Canvas to let users erase the top layer with their mouse or finger, revealing a promo code or secret message underneath.

Size
2.2 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
379
<div class="scratch-container">
  <div class="scratch-base">
    <h3>You Won!</h3>
    <div class="code">CODE2026</div>
  </div>
  <canvas id="scratchCanvas" width="300" height="150"></canvas>
</div>
.scratch-container {
  font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  position: relative;
  width: 300px;
  height: 150px;
  margin: 0 auto;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.scratch-base {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #10b981, #059669);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  z-index: 1;
}
.scratch-base h3 {
  margin: 0 0 10px 0;
  font-size: 1.5rem;
}
.code {
  background: white;
  color: #333;
  padding: 5px 15px;
  border-radius: 4px;
  font-family: monospace;
  font-weight: 700;
  letter-spacing: 2px;
}
canvas {
  position: relative;
  z-index: 2;
  cursor: crosshair;
}
const canvas = document.getElementById("scratchCanvas");
const ctx = canvas.getContext("2d");
let isDrawing = false;

// Fill with gray overlay
ctx.fillStyle = "#9ca3af";
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Add text instruction
ctx.fillStyle = "#ffffff";
ctx.font = "16px Arial";
ctx.fillText("Scratch Here!", 100, 80);

// Set blend mode to erase
ctx.globalCompositeOperation = "destination-out";

function scratch(x, y) {
  ctx.beginPath();
  ctx.arc(x, y, 15, 0, 2 * Math.PI);
  ctx.fill();
}

canvas.addEventListener("mousedown", () => isDrawing = true);
canvas.addEventListener("mouseup", () => isDrawing = false);
canvas.addEventListener("mousemove", (e) => {
  if (isDrawing) {
    const rect = canvas.getBoundingClientRect();
    scratch(e.clientX - rect.left, e.clientY - rect.top);
  }
});

// Touch support
canvas.addEventListener("touchstart", (e) => {
  isDrawing = true;
  e.preventDefault();
});
canvas.addEventListener("touchend", () => isDrawing = false);
canvas.addEventListener("touchmove", (e) => {
  if (isDrawing) {
    const rect = canvas.getBoundingClientRect();
    const touch = e.touches[0];
    scratch(touch.clientX - rect.left, touch.clientY - rect.top);
  }
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save