Ir al contenido
Evaluar mi proyecto
Componentes · FondosDisponible

Fondo de lluvia digital

Columnas de caracteres que caen con estela y cabeza brillante, en canvas, con pausa fuera de pantalla.

Despierta, operador

Código completo

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

fondo-matrix.tsx115 líneas
Descargar
"use client";

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

/** Fondo de lluvia digital en canvas: columnas de caracteres que caen con estela y cabeza brillante. Pausa fuera de pantalla y con botón. React + TypeScript, sin dependencias. */
export type FondoMatrixProps = {
  color?: string;
  chars?: string;
  fontSize?: number;
  children?: ReactNode;
  className?: string;
  style?: CSSProperties;
};

const CSS = `
.gcfmx-root { box-sizing: border-box; position: relative; isolation: isolate; container-type: inline-size; width: 100%; min-height: 480px; overflow: hidden; display: grid; place-items: center; background: #010503; color: #c9ffd8; font: 500 16px/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace; }
.gcfmx-root *, .gcfmx-root *::before, .gcfmx-root *::after { box-sizing: border-box; }
.gcfmx-root :focus-visible { outline: 2px solid #3dff7a; outline-offset: 3px; }
.gcfmx-canvas { position: absolute; inset: 0; z-index: -1; width: 100%; height: 100%; display: block; }
.gcfmx-pause { position: absolute; right: 14px; bottom: 14px; z-index: 3; display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px; border: 1px solid #1d6a35; border-radius: 4px; background: rgba(1, 8, 4, .8); color: #3dff7a; font: 600 12px/1 ui-monospace, "SF Mono", Menlo, monospace; cursor: pointer; }
.gcfmx-pause:hover { background: #3dff7a; color: #010503; }`;

export function FondoMatrix({ color = "#3dff7a", chars = "01アイウエオカキクケコサシスセソタチツテトナニヌネノ<>/{}[]=+-*", fontSize = 16, children, className = "", style }: FondoMatrixProps) {
  const root = useRef<HTMLElement>(null);
  const canvas = useRef<HTMLCanvasElement>(null);
  const [paused, setPaused] = useState(false);
  const pausedRef = useRef(false);
  useEffect(() => {
    pausedRef.current = paused;
  }, [paused]);
  const startRef = useRef<() => void>(() => {});

  useEffect(() => {
    const wrap = root.current;
    const cv = canvas.current;
    const ctx = cv?.getContext("2d");
    if (!wrap || !cv || !ctx) return;
    const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const glyphs = Array.from(chars);
    let w = 0, h = 0, dpr = 1, raf = 0, visible = true, last = 0;
    let drops: number[] = [];

    function size() {
      const r = wrap!.getBoundingClientRect();
      dpr = Math.min(window.devicePixelRatio || 1, 2);
      w = r.width; h = r.height;
      cv!.width = Math.round(w * dpr); cv!.height = Math.round(h * dpr);
      const cols = Math.ceil(w / fontSize);
      drops = Array.from({ length: cols }, (_, i) => drops[i] ?? Math.floor(Math.random() * -40));
    }
    function frame(now: number) {
      if (!ctx) return;
      if (now - last > 50 || reduced) {
        last = now;
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        ctx.fillStyle = "rgba(1, 5, 3, .12)";
        ctx.fillRect(0, 0, w, h);
        ctx.font = `${fontSize}px ui-monospace, Menlo, monospace`;
        for (let i = 0; i < drops.length; i++) {
          const ch = glyphs[Math.floor(Math.random() * glyphs.length)];
          const x = i * fontSize;
          const y = drops[i] * fontSize;
          ctx.fillStyle = "#e6ffee";
          ctx.fillText(ch, x, y);
          ctx.fillStyle = color;
          ctx.fillText(glyphs[Math.floor(Math.random() * glyphs.length)], x, y - fontSize);
          if (y > h && Math.random() > 0.972) drops[i] = 0;
          drops[i]++;
        }
      }
      raf = !reduced && visible && !pausedRef.current && !document.hidden ? requestAnimationFrame(frame) : 0;
    }
    const start = () => { if (!raf) raf = requestAnimationFrame(frame); };
    startRef.current = start;
    size();
    ctx.fillStyle = "#010503";
    ctx.fillRect(0, 0, cv.width, cv.height);
    if (reduced) for (let i = 0; i < 40; i++) frame(i * 100);
    else start();
    const ro = new ResizeObserver(() => { size(); start(); });
    ro.observe(wrap);
    const io = new IntersectionObserver(([e]) => { visible = e.isIntersecting; if (visible) start(); });
    io.observe(wrap);
    const vis = () => !document.hidden && start();
    document.addEventListener("visibilitychange", vis);
    return () => {
      cancelAnimationFrame(raf);
      ro.disconnect(); io.disconnect();
      document.removeEventListener("visibilitychange", vis);
    };
  }, [color, chars, fontSize]);

  return (
    <section ref={root} className={`gcfmx-root ${className}`} style={style}>
      <style>{CSS}</style>
      <canvas ref={canvas} className="gcfmx-canvas" aria-hidden="true" />
      {children}
      <button
        className="gcfmx-pause"
        type="button"
        aria-pressed={paused}
        onClick={() => {
          setPaused((value) => {
            if (value) setTimeout(() => startRef.current(), 0);
            return !value;
          });
        }}
      >
        <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">{paused ? <path d="M7 4v16l13-8z" /> : <path d="M6 4h4v16H6zM14 4h4v16h-4z" />}</svg>
        {paused ? "reanudar" : "pausar"} fondo
      </button>
    </section>
  );
}

Úsalo en tu proyecto

Instálalo con la CLI de shadcn.

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

Ejemplo de uso de Fondo de lluvia digital

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

ejemplo.tsx5 líneas
import { FondoMatrix } from "./fondo-matrix";

export default function Ejemplo() {
  return <FondoMatrix color="Ejemplo">Contenido</FondoMatrix>;
}

Propiedades de FondoMatrix

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

PropiedadTipoDescripción
color?stringOpcional.
chars?stringOpcional.
fontSize?numberOpcional.
children?ReactNodeOpcional.
className?stringOpcional.
style?CSSPropertiesOpcional.

Accesibilidad y rendimiento

El archivo tiene 115 líneas (5 KB) y no necesita @keyframes. Esto es lo que hace Fondo de lluvia digital 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).
  • Expone su estado a tecnologías de apoyo con atributos aria-*.
  • Dibuja en <canvas>, sin imágenes ni librerías gráficas.
  • Se pausa cuando sale de la pantalla para no gastar batería ni CPU.
  • 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)