Constellation

Points wandering on slow loops, joined by a fine line whenever two come close.

Options

Screen
Colour

Code

import { useEffect, useRef } from "react";
import "./constellation.css";

function paint(ctx, w, h, t, colour) {
  const rnd = (i) => { const x = Math.sin(i * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); };
  const reach = 170;
  const points = [];
  for (let i = 0; i < 64; i++) {
    points.push([
      w * (0.5 + 0.48 * Math.sin(t * (0.05 + rnd(i) * 0.08) + rnd(i + 1) * 6.283)),
      h * (0.5 + 0.46 * Math.cos(t * (0.04 + rnd(i + 2) * 0.08) + rnd(i + 3) * 6.283)),
    ]);
  }
  ctx.strokeStyle = colour;
  ctx.fillStyle = colour;
  ctx.lineWidth = 1;
  for (let a = 0; a < points.length; a++) {
    for (let b = a + 1; b < points.length; b++) {
      const distance = Math.hypot(points[a][0] - points[b][0], points[a][1] - points[b][1]);
      if (distance > reach) continue;
      ctx.globalAlpha = (1 - distance / reach) * 0.45;
      ctx.beginPath();
      ctx.moveTo(points[a][0], points[a][1]);
      ctx.lineTo(points[b][0], points[b][1]);
      ctx.stroke();
    }
  }
  ctx.globalAlpha = 0.7;
  for (const [x, y] of points) {
    ctx.beginPath();
    ctx.arc(x, y, 1.8, 0, Math.PI * 2);
    ctx.fill();
  }
}

export function Constellation({ children }) {
  const ref = useRef(null);

  useEffect(() => {
    const canvas = ref.current;
    const ctx = canvas.getContext("2d");
    const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
    let w = 0;
    let h = 0;
    let frame = 0;
    let seen = true;

    const draw = (now) => {
      frame = 0;
      ctx.clearRect(0, 0, w, h);
      ctx.globalAlpha = 1;
      paint(ctx, w, h, now / 1000, getComputedStyle(canvas).color);
      if (seen && !still) frame = requestAnimationFrame(draw);
    };
    const start = () => {
      if (!frame) frame = requestAnimationFrame(draw);
    };

    const sized = new ResizeObserver(() => {
      const ratio = Math.min(window.devicePixelRatio || 1, 2);
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * ratio;
      canvas.height = h * ratio;
      ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
      start();
    });
    const watched = new IntersectionObserver(([entry]) => {
      seen = entry.isIntersecting;
      if (seen) start();
    });
    sized.observe(canvas);
    watched.observe(canvas);

    return () => {
      cancelAnimationFrame(frame);
      sized.disconnect();
      watched.disconnect();
    };
  }, []);

  return (
    <section className="dh-links">
      <canvas ref={ref} className="dh-links-art" aria-hidden="true" />
      <div className="dh-links-content">{children}</div>
    </section>
  );
}