Ir al contenido
Evaluar mi proyecto
Componentes · Cursor y efectosDisponible

Botón con lluvia de confeti

Confeti con física (gravedad, rozamiento y giro) sobre un canvas propio que se destruye al terminar; respeta movimiento reducido.

Código completo

Es exactamente el archivo que se descarga. Cópialo a tu proyecto y úsalo.

efecto-confeti.tsx87 líneas
Descargar
"use client";

import { useEffect, useRef, type CSSProperties } from "react";

/** Botón de celebración: al pulsarlo lanza confeti con física (gravedad, rozamiento y giro) sobre un canvas propio que se destruye al terminar. Se omite con movimiento reducido, manteniendo el mensaje de confirmación. React + TypeScript, sin dependencias. */
export type EfectoConfetiProps = {
  label?: string;
  message?: string;
  count?: number;
  onFire?: () => void;
  className?: string;
  style?: CSSProperties;
};

const CSS = `
.gcecf-root { box-sizing: border-box; position: relative; display: inline-grid; justify-items: center; gap: 14px; font: 700 16px/1.2 ui-rounded, "SF Pro Rounded", ui-sans-serif, system-ui, sans-serif; color: #2b1a4a; }
.gcecf-root *, .gcecf-root *::before, .gcecf-root *::after { box-sizing: border-box; }
.gcecf-root button { font: inherit; -webkit-tap-highlight-color: transparent; }
.gcecf-root :focus-visible { outline: 3px solid #2b1a4a; outline-offset: 4px; }
.gcecf-btn { position: relative; min-height: 60px; padding: 0 34px; border: 0; border-radius: 999px; background: #ffd23f; color: #2b1a4a; font-weight: 800; font-size: 18px; cursor: pointer; box-shadow: inset -5px -7px 12px rgba(190, 120, 0, .35), inset 5px 7px 12px rgba(255, 255, 255, .6), 0 12px 20px -8px rgba(190, 120, 0, .5); transition: transform .3s cubic-bezier(.34, 1.56, .64, 1); }
.gcecf-btn:hover { transform: translateY(-3px) scale(1.04); }
.gcecf-btn:active { transform: scale(.94, .9); }
.gcecf-msg { min-height: 20px; font-size: 14px; color: #6a4a8c; }
@media (prefers-reduced-motion: reduce) { .gcecf-btn { transition: none; } }`;

const COLORS = ["#ff4d6d", "#ffd23f", "#4ade80", "#38bdf8", "#a78bfa", "#fb923c"];

export function EfectoConfeti({ label = "¡Lo logramos!", message = "Proyecto entregado", count = 120, onFire, className = "", style }: EfectoConfetiProps) {
  const btn = useRef<HTMLButtonElement>(null);
  const msg = useRef<HTMLSpanElement>(null);
  const live = useRef(0);
  useEffect(() => () => { document.querySelectorAll("canvas[data-gcecf]").forEach((n) => n.remove()); }, []);

  function fire() {
    onFire?.();
    if (msg.current) msg.current.textContent = message;
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
    const rect = btn.current!.getBoundingClientRect();
    const ox = rect.left + rect.width / 2, oy = rect.top + rect.height / 2;
    const cv = document.createElement("canvas");
    cv.dataset.gcecf = "1";
    const dpr = Math.min(window.devicePixelRatio || 1, 2);
    const W = window.innerWidth, H = window.innerHeight;
    cv.width = W * dpr; cv.height = H * dpr;
    Object.assign(cv.style, { position: "fixed", inset: "0", width: "100%", height: "100%", pointerEvents: "none", zIndex: "9999" });
    document.body.appendChild(cv);
    const ctx = cv.getContext("2d")!;
    ctx.scale(dpr, dpr);
    type P = { x: number; y: number; vx: number; vy: number; r: number; vr: number; w: number; h: number; c: string; life: number };
    const parts: P[] = Array.from({ length: count }, () => {
      const a = -Math.PI / 2 + (Math.random() - 0.5) * 1.8;
      const s = 7 + Math.random() * 9;
      return { x: ox, y: oy, vx: Math.cos(a) * s, vy: Math.sin(a) * s, r: Math.random() * 6, vr: (Math.random() - 0.5) * 0.4, w: 6 + Math.random() * 6, h: 3 + Math.random() * 5, c: COLORS[Math.floor(Math.random() * COLORS.length)], life: 1 };
    });
    live.current++;
    const step = () => {
      ctx.clearRect(0, 0, W, H);
      let alive = 0;
      for (const p of parts) {
        p.vy += 0.34; p.vx *= 0.985; p.vy *= 0.985;
        p.x += p.vx; p.y += p.vy; p.r += p.vr;
        p.life -= 0.0075;
        if (p.life <= 0 || p.y > H + 20) continue;
        alive++;
        ctx.save();
        ctx.translate(p.x, p.y);
        ctx.rotate(p.r);
        ctx.globalAlpha = Math.min(1, p.life * 2);
        ctx.fillStyle = p.c;
        ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h * Math.abs(Math.cos(p.r * 2)) + 1);
        ctx.restore();
      }
      if (alive && !document.hidden) requestAnimationFrame(step);
      else { cv.remove(); live.current--; }
    };
    requestAnimationFrame(step);
  }

  return (
    <div className={`gcecf-root ${className}`} style={style}>
      <style>{CSS}</style>
      <button ref={btn} className="gcecf-btn" type="button" onClick={fire}>{label}</button>
      <span ref={msg} className="gcecf-msg" role="status" aria-live="polite" />
    </div>
  );
}

Úsalo en tu proyecto

Instálalo con la CLI de shadcn.

terminal.sh1 líneas
npx shadcn@latest add https://www.gassierconsulting.com/r/efecto-confeti

Ejemplo de uso de Botón con lluvia de confeti

Después de copiar efecto-confeti.tsx a tu proyecto, impórtalo y colócalo donde lo necesites.

ejemplo.tsx5 líneas
import { EfectoConfeti } from "./efecto-confeti";

export default function Ejemplo() {
  return <EfectoConfeti label="Ejemplo" />;
}

Propiedades de EfectoConfeti

EfectoConfeti acepta 6 propiedades: todas son opcionales y tienen un valor por defecto, así que funciona sin configurar nada.

PropiedadTipoDescripción
label?stringOpcional.
message?stringOpcional.
count?numberOpcional.
onFire?() => voidOpcional.
className?stringOpcional.
style?CSSPropertiesOpcional.

Accesibilidad y rendimiento

El archivo tiene 87 líneas (4 KB) y no necesita @keyframes. Esto es lo que hace Botón con lluvia de confeti por quien lo usa:

  • Detecta prefers-reduced-motion y baja o quita el movimiento cuando la persona lo pide.
  • Muestra un anillo de foco visible al navegar con teclado (:focus-visible).
  • Declara roles ARIA para lectores de pantalla: status.
  • Anima con requestAnimationFrame, sincronizado con el refresco de pantalla.
  • Es un componente de cliente de Next.js: incluye la directiva "use client".
Licencia
MIT
Dependencias
React >=18
Compatibilidad
React 18 y 19 · Next.js (componente de cliente)