Wie man ein Cupón Rasca und Gana Interaktiv mit Canvas HTML5 und Partículas von Confeti

Schnellübersicht

Ein cupón interaktiv von rasca und gana superpone ein Element <canvas> pintado mit ein degradado metálico über eine tarjeta mit der premio oculto. Al arrastrar der ratón oder deslizar der dedo, se borra der área pintada verwendet die operación von composición ctx.globalCompositeOperation = "destination-out". Ein análisis von píxeles mit ctx.getImageData() berechnet der porcentaje rascado und revela der premio mit confeti al superar der 50%.

Interaktive Demo Live-Vorschau
🎉 You Won!
SAVE30
Use code at checkout
🪙 Rub cursor over card to scratch metallic foil

Schritt 1: Superposición vom Premio Oculto und der Lienzo Canvas

Ubica der contenedor vom premio in eine posición relativa und sitúa der Element <canvas> von Form absoluta directamente encima für bloquear die vista inicial.

scratch-card.html
<div class="scratch-card-container">
  <!-- Tarjeta con el código de descuento o premio oculto -->
  <div class="scratch-reward">
    <span class="reward-tag">PREMIO DESCUBIERTO!</span>
    <h3 class="reward-code">SAVE50NOW</h3>
    <p class="reward-desc">50% de descuento en tu próximo pedido</p>
    <button class="reward-copy-btn" onclick="navigator.clipboard.writeText('SAVE50NOW')">Copiar Código</button>
  </div>
  <!-- Lienzo interactivo de raspado -->
  <canvas id="scratchCanvas" width="340" height="200" class="scratch-canvas"></canvas>
</div>

Schritt 2: Pintado von die Capa Metálica mit Degradados in Canvas

Inicializa der contexto 2D vom lienzo und erstellt ein degradado lineal que simule die apariencia plateada oder dorada brillante vom material rascable von eine lotería.

scratch-foil.js
const canvas = document.getElementById('scratchCanvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });

function initFoil() {
  const grad = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
  grad.addColorStop(0, '#94a3b8');
  grad.addColorStop(0.3, '#cbd5e1');
  grad.addColorStop(0.6, '#64748b');
  grad.addColorStop(1, '#94a3b8');

  ctx.fillStyle = grad;
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // Texto decorativo sobre la capa rascable
  ctx.fillStyle = '#1e293b';
  ctx.font = 'bold 16px sans-serif';
  ctx.textAlign = 'center';
  ctx.fillText('Rasca aquí para descubrir tu regalo!', canvas.width / 2, canvas.height / 2);
}

initFoil();

Schritt 3: Borrado von Píxeles mit destination-out und Eventos Táctiles

Al hacer clic und arrastrar, establece globalCompositeOperation = "destination-out" für que die trazos von pincel conviertan die píxeles vom lienzo in transparentes.

scratch-engine.js
let isDrawing = false;

function scratch(x, y) {
  ctx.globalCompositeOperation = 'destination-out';
  ctx.beginPath();
  ctx.arc(x, y, 22, 0, Math.PI * 2);
  ctx.fill();
  checkScratchPercentage();
}

function getPos(e) {
  const rect = canvas.getBoundingClientRect();
  const clientX = e.touches ? e.touches[0].clientX : e.clientX;
  const clientY = e.touches ? e.touches[0].clientY : e.clientY;
  return {
    x: clientX - rect.left,
    y: clientY - rect.top
  };
}

canvas.addEventListener('mousedown', (e) => { isDrawing = true; const p = getPos(e); scratch(p.x, p.y); });
canvas.addEventListener('mousemove', (e) => { if (!isDrawing) return; const p = getPos(e); scratch(p.x, p.y); });
window.addEventListener('mouseup', () => { isDrawing = false; });

// Soporte para pantallas táctiles móviles
canvas.addEventListener('touchstart', (e) => { isDrawing = true; const p = getPos(e); scratch(p.x, p.y); e.preventDefault(); });
canvas.addEventListener('touchmove', (e) => { if (!isDrawing) return; const p = getPos(e); scratch(p.x, p.y); e.preventDefault(); });
window.addEventListener('touchend', () => { isDrawing = false; });

Schritt 4: Cálculo von Porcentaje Revelado mit getImageData

Muestrea die canales alfa von die píxeles cada 250ms. Wenn mehr vom 50% von die píxeles sean transparentes, desvanece der lienzo durch vollständig für eine revelación triunfal.

scratch-threshold.js
let isRevealed = false;

function checkScratchPercentage() {
  if (isRevealed) return;
  
  const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const pixels = imgData.data;
  let transparentCount = 0;
  const sampleRate = 32; // Muestrear cada 32 píxeles para máximo rendimiento
  
  for (let i = 3; i < pixels.length; i += 4 * sampleRate) {
    if (pixels[i] === 0) transparentCount++;
  }
  
  const totalSampled = pixels.length / (4 * sampleRate);
  const percent = (transparentCount / totalSampled) * 100;
  
  if (percent > 45) {
    isRevealed = true;
    canvas.style.transition = 'opacity 0.6s ease';
    canvas.style.opacity = '0';
    setTimeout(() => { canvas.style.display = 'none'; }, 600);
    triggerConfetti();
  }
}

function triggerConfetti() {
  console.log('Premio completamente revelado!');
}

Erweiterte Best Practices & Vertiefung

Erweitere diese Implementierung durch die Kombination mit ergänzenden Werkzeugen und Design-Tokens:

1. Borrado mit Operador Destination-Out in Canvas

Im Generator von Cupón Rasca und Gana öffnen →

Técnica von recorte alfa native que borra der Farbe existente revelando mit Präzision quirúrgica der contenido debajo.

CLEARED: 62% [AUTO-REVEAL]

2. Detección Schnelle von Umbral Rascado

Im Generator von Cupón Rasca und Gana öffnen →

Muestreo optimizado von datos alfa a intervalos controlados für no saturar der Haupt-Thread vom Browser.

3. Verläufe Metálicos Plateados und Dorados

Im Generator von Cupón Rasca und Gana öffnen →

Farbverläufe realistas mit Glanz-Effekte especulares und textura reflectante similares a die tarjetas von raspado impresas.

Chaam
Chaams Profi-Tipp

Beim Entwickeln von performanten UI-Animationen oder Partikelsystemen gilt meine Faustregel: Berechne niemals Layout-Eigenschaften (wie getBoundingClientRect() oder offsetHeight) innerhalb von Animations-Schleifen. Führe Messungen einmalig vorab durch und nutze GPU-beschleunigte CSS-Transforms oder Canvas für stabile 60 fps.

Listo für erstellen cupones interaktive von rasca und gana?

Generiert tarjetas von rasca und gana mit texturas metálicas doradas oder plateadas, cálculos von raspado und celebración mit confeti.

Im Generator von Cupón Rasca und Gana öffnen ↗

Häufig gestellte Fragen (FAQ)

Praxisnahe Antworten zu Implementierung, Browser-Besonderheiten und Performance-Tipps.

Wie funciona globalCompositeOperation = "destination-out"?

Diese Regel von composición gráfica hace que cualquier Form dibujada actúe wie ein borrador, vaciando der canal alfa von die píxeles subyacentes in der lienzo für volverlos 100% transparentes.

Durch qué getImageData puede ralentizar Browser móviles und wie optimizarlo?

Escanear todos die píxeles (Breite × Höhe × 4 canales) exige mucha Speicher. Die Lösung es muestrear sólo 1 von cada 32 píxeles (step = 4 * 32), reduciendo der trabajo in ein 97% ohne perder Präzision in der porcentaje.

Wie evitar que die Seite haga scroll al raspar in Bildschirme táctiles?

Es indispensable llamar a und.preventDefault() in die controladores von eventos touchstart und touchmove, oder bien declarar touch-action: none in der CSS vom Element canvas.

Der cupón rasca und gana es barrierefrei für personas mit discapacidades motrices?

Debe incluirse ein Button barrierefrei alternativo wie "Revelar cupón directamente" que elimine der lienzo mediante teclado für quienes no pueden realizar gestos von arrastre fino.

Se puede cambiar der Größe vom pincel von raspado dinámicamente?

Sí. Puedes anpassen der radio vom arco in ctx.arc(x, und, brushRadius, 0, Math.PI * 2). Ein radio von zwischen 20px und 28px suele ser der punto óptimo von ergonomía.

← Zurück zu allen Blog-Artikeln Generator-Studio starten →