Ir al contenido
Evaluar mi proyecto
Componentes · FondosDisponible

Fondo de campo de flujo generativo

Miles de trazos finos siguen una corriente que cambia lentamente y dibujan una caligrafía generativa sobre papel.

Trazos que fluyen

Código completo

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

fondo-flujo.tsx118 líneas
Descargar
"use client";

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

/** Fondo de campo de flujo en canvas: miles de trazos siguen una corriente que cambia lentamente y dibujan una caligrafía generativa. Pausa fuera de pantalla y con botón. React + TypeScript, sin dependencias. */
export type FondoFlujoProps = {
  ink?: string;
  paper?: string;
  count?: number;
  children?: ReactNode;
  className?: string;
  style?: CSSProperties;
};

const CSS = `
.gcffl-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; color: #1c1a17; font: 500 16px/1.5 "Newsreader", Georgia, ui-serif, serif; }
.gcffl-root *, .gcffl-root *::before, .gcffl-root *::after { box-sizing: border-box; }
.gcffl-root :focus-visible { outline: 2px solid #1c1a17; outline-offset: 3px; }
.gcffl-canvas { position: absolute; inset: 0; z-index: -1; width: 100%; height: 100%; display: block; }
.gcffl-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 #1c1a17; border-radius: 999px; background: rgba(240, 235, 224, .9); color: #1c1a17; font: 600 12px/1 ui-sans-serif, system-ui, sans-serif; cursor: pointer; }
.gcffl-pause:hover { background: #fff; }`;

type P = { x: number; y: number; life: number };

export function FondoFlujo({ ink = "#1c1a17", paper = "#f0ebe0", count = 600, children, className = "", style }: FondoFlujoProps) {
  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;
    let w = 0, h = 0, dpr = 1, raf = 0, visible = true, t = 0;
    let parts: P[] = [];
    const angle = (x: number, y: number) => Math.sin(x * 0.004 + t) * 2 + Math.cos(y * 0.005 - t * 0.7) * 2 + Math.sin((x + y) * 0.0025) * 1.5;

    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);
      ctx!.setTransform(dpr, 0, 0, dpr, 0, 0);
      ctx!.fillStyle = paper;
      ctx!.fillRect(0, 0, w, h);
      parts = Array.from({ length: count }, () => ({ x: Math.random() * w, y: Math.random() * h, life: Math.random() * 200 }));
    }
    function step() {
      if (!ctx) return;
      ctx.strokeStyle = ink;
      ctx.globalAlpha = 0.07;
      ctx.lineWidth = 0.9;
      ctx.beginPath();
      for (const p of parts) {
        const a = angle(p.x, p.y);
        const nx = p.x + Math.cos(a) * 1.6;
        const ny = p.y + Math.sin(a) * 1.6;
        ctx.moveTo(p.x, p.y);
        ctx.lineTo(nx, ny);
        p.x = nx; p.y = ny; p.life--;
        if (p.life < 0 || p.x < 0 || p.x > w || p.y < 0 || p.y > h) { p.x = Math.random() * w; p.y = Math.random() * h; p.life = 120 + Math.random() * 160; }
      }
      ctx.stroke();
      ctx.globalAlpha = 1;
      t += 0.0009;
    }
    function frame() {
      step();
      raf = !reduced && visible && !pausedRef.current && !document.hidden ? requestAnimationFrame(frame) : 0;
    }
    const start = () => { if (!raf) raf = requestAnimationFrame(frame); };
    startRef.current = start;
    size();
    if (reduced) for (let i = 0; i < 260; i++) step();
    else start();
    const ro = new ResizeObserver(() => { size(); if (reduced) for (let i = 0; i < 260; i++) step(); 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);
    };
  }, [ink, paper, count]);

  return (
    <section ref={root} className={`gcffl-root ${className}`} style={style}>
      <style>{CSS}</style>
      <canvas ref={canvas} className="gcffl-canvas" aria-hidden="true" />
      {children}
      <button
        className="gcffl-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-flujo

Ejemplo de uso de Fondo de campo de flujo generativo

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

ejemplo.tsx5 líneas
import { FondoFlujo } from "./fondo-flujo";

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

Propiedades de FondoFlujo

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

PropiedadTipoDescripción
ink?stringOpcional.
paper?stringOpcional.
count?numberOpcional.
children?ReactNodeOpcional.
className?stringOpcional.
style?CSSPropertiesOpcional.

Accesibilidad y rendimiento

El archivo tiene 118 líneas (5 KB) y no necesita @keyframes. Esto es lo que hace Fondo de campo de flujo generativo 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)