Ridgelines

Row on row of fine lines rising into peaks in the middle, each hiding the ones behind it, all slowly shifting.

A signal, from far away.

Rows of fine lines rising into peaks, each hiding the ones behind.

Options

Screen
Colour

Code

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

function paint(ctx, w, h, t, colour) {
  const rows = 30;
  ctx.strokeStyle = colour;
  ctx.lineWidth = 1.2;
  ctx.lineJoin = "round";
  for (let row = 0; row < rows; row++) {
    const base = h * (0.2 + row * 0.027);
    const trace = () => {
      ctx.beginPath();
      for (let x = 0; x <= w; x += 6) {
        const middle = Math.exp(-Math.pow((x - w / 2) / (w * 0.2), 2));
        const peak = Math.sin(x * 0.021 + row * 1.7 + t * 0.6) + Math.sin(x * 0.047 - row * 0.9 - t * 0.9) + Math.sin(x * 0.011 + row + t * 0.3);
        ctx.lineTo(x, base - (Math.abs(peak) / 3) * middle * h * 0.17 - Math.sin(x * 0.09 + row * 2.1 + t) * 1.5);
      }
    };
    trace();
    ctx.lineTo(w, h);
    ctx.lineTo(0, h);
    ctx.globalCompositeOperation = "destination-out";
    ctx.globalAlpha = 1;
    ctx.fill();
    trace();
    ctx.globalCompositeOperation = "source-over";
    ctx.globalAlpha = 0.2 + 0.5 * (row / rows);
    ctx.stroke();
  }
}

export function Ridgelines({ 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-ridges">
      <canvas ref={ref} className="dh-ridges-art" aria-hidden="true" />
      <div className="dh-ridges-content">{children}</div>
    </section>
  );
}

A signal, from far away.

Rows of fine lines rising into peaks, each hiding the ones behind.