Canvas · Avanzado · visto en PHR
Red de puntos que reacciona al mouse
La idea del cerebro de neuronas de PHR en su versión simple: puntos que se mueven, se conectan y se encienden al acercar el puntero.
Cómo se construye
- 1Genera N puntos con posición y velocidad lenta; con una semilla fija para que salga igual siempre.
- 2En cada cuadro mueve los puntos y dibuja líneas entre los que estén a menos de cierta distancia.
- 3La opacidad de la línea baja con la distancia; el puntero 'enciende' los puntos cercanos.
- 4Limita el número de puntos según el ancho de pantalla y pausa fuera de vista.
Pídeselo a Claude
Copia este prompt tal cual. Está escrito con los detalles que Claude suele olvidar.
Prompt para Claude
Crea un componente <canvas> con una red de 70 puntos (40 en pantallas <640px). Cada punto se mueve lento y rebota en los bordes. Dibuja una línea entre puntos a menos de 110 px con opacidad proporcional a la cercanía. Los puntos a menos de 140 px del puntero se agrandan y se pintan en #D1FE17. Posiciones iniciales con un generador pseudoaleatorio con semilla (para que sea determinista). Escala por devicePixelRatio, pausa con IntersectionObserver y limpia todo al desmontar. Con prefers-reduced-motion dibuja un solo cuadro.
El código
Así queda la pieza ya construida (red.tsx).
red.tsx
"use client";
import { useEffect, useRef } from "react";
const azar = (s: number) => () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296);
export function Red() {
const ref = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const c = ref.current!, ctx = c.getContext("2d")!;
const r = azar(7), quieto = matchMedia("(prefers-reduced-motion: reduce)").matches;
let w = 0, h = 0, raf = 0, visible = true, mx = -999, my = -999;
const N = innerWidth < 640 ? 40 : 70;
const p = Array.from({ length: N }, () => ({ x: r(), y: r(), vx: (r() - 0.5) * 0.0004, vy: (r() - 0.5) * 0.0004 }));
const medir = () => {
const dpr = Math.min(devicePixelRatio || 1, 2);
w = c.clientWidth; h = c.clientHeight; c.width = w * dpr; c.height = h * dpr;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
};
const cuadro = () => {
ctx.clearRect(0, 0, w, h);
for (const a of p) { a.x += a.vx * 16; a.y += a.vy * 16; if (a.x < 0 || a.x > 1) a.vx *= -1; if (a.y < 0 || a.y > 1) a.vy *= -1; }
for (let i = 0; i < N; i++) {
const a = p[i], ax = a.x * w, ay = a.y * h;
for (let j = i + 1; j < N; j++) {
const b = p[j], d = Math.hypot(ax - b.x * w, ay - b.y * h);
if (d < 110) { ctx.strokeStyle = `rgba(209,254,23,${(1 - d / 110) * 0.35})`; ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(b.x * w, b.y * h); ctx.stroke(); }
}
const cerca = Math.hypot(ax - mx, ay - my) < 140;
ctx.fillStyle = cerca ? "#D1FE17" : "rgba(244,244,240,.55)";
ctx.beginPath(); ctx.arc(ax, ay, cerca ? 3.5 : 2, 0, 7); ctx.fill();
}
};
const bucle = () => { if (visible) cuadro(); raf = requestAnimationFrame(bucle); };
const mover = (e: PointerEvent) => { const b = c.getBoundingClientRect(); mx = e.clientX - b.left; my = e.clientY - b.top; };
medir();
const ro = new ResizeObserver(medir); ro.observe(c);
const io = new IntersectionObserver(([e]) => (visible = e.isIntersecting)); io.observe(c);
c.addEventListener("pointermove", mover);
quieto ? cuadro() : (raf = requestAnimationFrame(bucle));
return () => { cancelAnimationFrame(raf); ro.disconnect(); io.disconnect(); c.removeEventListener("pointermove", mover); };
}, []);
return <canvas ref={ref} style={{ width: "100%", height: 320, touchAction: "pan-y" }} />;
}Error típico de Claude
Claude compara todos contra todos con 300 puntos y el celular se arrastra; o usa Math.random y la red cambia en cada visita.
Cómo evitarlo: Pídele un máximo de puntos por pantalla, semilla fija y pausa fuera de vista. Con 70 puntos son ~2.400 comparaciones: está bien; con 300 no.