Star streak background

A night-sky backdrop for heroes and cards. Three depths of twinkling, slowly drifting stars are drawn on one sharp, resolution-aware canvas, thin glowing streaks with tapered tails shoot across at random intervals, and a faint haze from your chart colours sits on top. Set the streak angle and colour, use it as a dark night sky or a light paper sky with ink specks and pencil streaks, or let it follow the theme. Clicking empty sky fires a streak from the pointer, and an optional constellation mode joins nearby stars to the pointer with hairlines. It pauses when off screen or in a hidden tab, caps at 60 frames a second, stays out of the way of content and clicks layered on top, and shows a still star field when reduced motion is on.

BackgroundsComponentTailwind v4

Source

"use client";

import { useEffect, useRef, type CSSProperties, type PointerEvent, type ReactNode } from "react";
import { cn } from "@/lib/utils";

export type StarStreakBackgroundProps = {
  /** Stars per 10,000 square pixels. */
  density?: number;
  /** A new streak appears after a random wait in this range, in milliseconds. */
  streakEvery?: [number, number];
  /** Direction streaks travel, in degrees: 0 is to the right, 90 is straight down. */
  angle?: number;
  /** "auto" follows the page theme; "dark" is a night sky and "light" a paper sky, whatever the theme. */
  tone?: "auto" | "dark" | "light";
  /** Colour of stars and streaks. Defaults to the sky's foreground colour. */
  color?: string;
  /** Click or tap empty sky to send a streak from that point. */
  interactive?: boolean;
  /** Join stars near the pointer to it with fine lines. */
  constellation?: boolean;
  children?: ReactNode;
  className?: string;
};

type Star = { x: number; y: number; r: number; a: number; f: number; p: number; layer: number };
type Streak = { x: number; y: number; vx: number; vy: number; len: number; life: number; age: number; w: number };

// A paper sky: warm off-white with ink. Tokens are overridden locally so content on top follows along.
const PAPER: CSSProperties = {
  "--background": "oklch(0.975 0.008 85)",
  "--foreground": "oklch(0.24 0.012 260)",
  "--card": "oklch(0.99 0.005 85)",
  "--card-foreground": "oklch(0.24 0.012 260)",
  "--muted": "oklch(0.94 0.01 85)",
  "--muted-foreground": "oklch(0.5 0.012 260)",
  "--border": "oklch(0.87 0.012 85)",
  "--primary": "oklch(0.24 0.012 260)",
  "--primary-foreground": "oklch(0.98 0.004 85)",
  "--accent": "oklch(0.93 0.012 85)",
  "--accent-foreground": "oklch(0.24 0.012 260)",
  colorScheme: "light",
} as CSSProperties;

const LAYERS = [
  { r: [0.45, 0.8], a: [0.35, 0.6], drift: 2.5 },
  { r: [0.75, 1.15], a: [0.55, 0.85], drift: 5 },
  { r: [1.1, 1.8], a: [0.8, 1], drift: 9 },
] as const;

// Turns any CSS colour (including oklch and color-mix) into rgb numbers the canvas can blend with alpha.
function toRgb(color: string, probe: CanvasRenderingContext2D) {
  probe.clearRect(0, 0, 1, 1);
  probe.fillStyle = "#000";
  probe.fillStyle = color;
  probe.fillRect(0, 0, 1, 1);
  const [r, g, b] = probe.getImageData(0, 0, 1, 1).data;
  return [r ?? 0, g ?? 0, b ?? 0] as const;
}

const between = (min: number, max: number) => min + Math.random() * (max - min);

export function StarStreakBackground({
  density = 2.6,
  streakEvery = [1400, 4200],
  angle = 152,
  tone = "auto",
  color,
  interactive = true,
  constellation = false,
  children,
  className,
}: StarStreakBackgroundProps) {
  const root = useRef<HTMLDivElement>(null);
  const canvas = useRef<HTMLCanvasElement>(null);
  const pointer = useRef({ x: 0, y: 0, active: false });
  const fire = useRef<(x?: number, y?: number) => void>(() => {});
  const settings = useRef({ density, streakEvery, angle, color, constellation });
  settings.current = { density, streakEvery, angle, color, constellation };

  useEffect(() => {
    const host = root.current;
    const node = canvas.current;
    const ctx = node?.getContext("2d");
    if (!host || !node || !ctx) return;
    const probeCanvas = document.createElement("canvas");
    probeCanvas.width = probeCanvas.height = 1;
    const probe = probeCanvas.getContext("2d", { willReadFrequently: true });

    const reduce = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
    let width = 0;
    let height = 0;
    let stars: Star[] = [];
    let streaks: Streak[] = [];
    let ink: readonly [number, number, number] = [255, 255, 255];
    let light = false;
    let nextStreak = 0;
    let time = 0;

    const readColors = () => {
      if (!probe) return;
      const style = getComputedStyle(host);
      ink = toRgb(settings.current.color || style.color, probe);
      const bg = toRgb(style.backgroundColor, probe);
      light = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] > 140;
    };

    const seed = () => {
      const count = Math.min(1400, Math.round((width * height * settings.current.density) / 10000));
      stars = Array.from({ length: count }, () => {
        const roll = Math.random();
        const layer = roll < 0.62 ? 0 : roll < 0.9 ? 1 : 2;
        const spec = LAYERS[layer]!;
        return { x: Math.random() * width, y: Math.random() * height, r: between(spec.r[0], spec.r[1]), a: between(spec.a[0], spec.a[1]), f: between(0.6, 2.4), p: Math.random() * Math.PI * 2, layer };
      });
    };

    const resize = () => {
      const rect = host.getBoundingClientRect();
      const dpr = Math.min(2, window.devicePixelRatio || 1);
      width = Math.max(1, Math.round(rect.width));
      height = Math.max(1, Math.round(rect.height));
      node.width = Math.round(width * dpr);
      node.height = Math.round(height * dpr);
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      seed();
      draw(0);
    };

    const spawn = (x?: number, y?: number) => {
      const rad = (settings.current.angle * Math.PI) / 180;
      const speed = between(780, 1250);
      const sx = x ?? between(width * 0.15, width * 1.05);
      const sy = y ?? between(-height * 0.05, height * 0.45);
      streaks.push({ x: sx, y: sy, vx: Math.cos(rad) * speed, vy: Math.sin(rad) * speed, len: between(90, 190), life: between(0.55, 1), age: 0, w: between(1.1, 1.8) });
    };
    fire.current = (x, y) => {
      if (reduce) return;
      spawn(x, y);
      start();
    };

    const rgba = (a: number) => `rgba(${ink[0]},${ink[1]},${ink[2]},${Math.max(0, Math.min(1, a)).toFixed(3)})`;

    function draw(dt: number) {
      time += dt;
      ctx!.clearRect(0, 0, width, height);
      const rad = (settings.current.angle * Math.PI) / 180;
      const dx = -Math.cos(rad);
      const dy = -Math.sin(rad);
      const dim = light ? 0.85 : 1;

      for (const star of stars) {
        const drift = LAYERS[star.layer]!.drift * dt * 0.35;
        star.x = (star.x + dx * drift + width) % width;
        star.y = (star.y + dy * drift + height) % height;
        const twinkle = reduce ? 1 : 0.6 + 0.4 * Math.sin(time * star.f + star.p);
        const alpha = star.a * twinkle * dim;
        if (star.layer === 2 && !light) {
          ctx!.fillStyle = rgba(alpha * 0.14);
          ctx!.beginPath();
          ctx!.arc(star.x, star.y, star.r * 3.2, 0, Math.PI * 2);
          ctx!.fill();
        }
        ctx!.fillStyle = rgba(alpha);
        if (star.r < 0.7) ctx!.fillRect(star.x - star.r, star.y - star.r, star.r * 2, star.r * 2);
        else {
          ctx!.beginPath();
          ctx!.arc(star.x, star.y, star.r, 0, Math.PI * 2);
          ctx!.fill();
        }
      }

      const p = pointer.current;
      if (settings.current.constellation && p.active) {
        ctx!.lineWidth = 0.6;
        for (const star of stars) {
          if (star.layer === 0) continue;
          const d = Math.hypot(star.x - p.x, star.y - p.y);
          if (d > 150) continue;
          ctx!.strokeStyle = rgba((1 - d / 150) * 0.45 * dim);
          ctx!.beginPath();
          ctx!.moveTo(p.x, p.y);
          ctx!.lineTo(star.x, star.y);
          ctx!.stroke();
        }
      }

      streaks = streaks.filter((s) => s.age < s.life);
      for (const s of streaks) {
        s.age += dt;
        s.x += s.vx * dt;
        s.y += s.vy * dt;
        const fadeIn = Math.min(1, s.age / 0.12);
        const alpha = Math.sin(Math.PI * Math.min(1, s.age / s.life)) * (light ? 0.75 : 1);
        const speed = Math.hypot(s.vx, s.vy) || 1;
        const tail = s.len * fadeIn;
        const tx = s.x - (s.vx / speed) * tail;
        const ty = s.y - (s.vy / speed) * tail;
        const gradient = ctx!.createLinearGradient(s.x, s.y, tx, ty);
        gradient.addColorStop(0, rgba(alpha));
        gradient.addColorStop(0.25, rgba(alpha * 0.45));
        gradient.addColorStop(1, rgba(0));
        ctx!.strokeStyle = gradient;
        ctx!.lineWidth = light ? s.w * 0.8 : s.w;
        ctx!.lineCap = "round";
        ctx!.beginPath();
        ctx!.moveTo(s.x, s.y);
        ctx!.lineTo(tx, ty);
        ctx!.stroke();
        if (!light) {
          const glow = ctx!.createRadialGradient(s.x, s.y, 0, s.x, s.y, 6);
          glow.addColorStop(0, rgba(alpha * 0.9));
          glow.addColorStop(1, rgba(0));
          ctx!.fillStyle = glow;
          ctx!.beginPath();
          ctx!.arc(s.x, s.y, 6, 0, Math.PI * 2);
          ctx!.fill();
        }
      }
    }

    let running = false;
    let visible = true;
    let frame = 0;
    let timer: ReturnType<typeof setTimeout> | undefined;
    let last = 0;

    const tick = () => {
      cancelAnimationFrame(frame);
      clearTimeout(timer);
      if (!running) return;
      const now = performance.now();
      const elapsed = now - last;
      // Cap at about 60 frames a second, even on faster screens.
      if (elapsed >= 15) {
        last = now;
        if (now >= nextStreak) {
          spawn();
          const [min, max] = settings.current.streakEvery;
          nextStreak = now + between(min, Math.max(min, max));
        }
        draw(Math.min(0.05, elapsed / 1000));
      }
      frame = requestAnimationFrame(tick);
      timer = setTimeout(tick, 40);
    };

    function start() {
      if (reduce || running || !visible || document.hidden) return;
      running = true;
      last = performance.now();
      if (!nextStreak) nextStreak = last + between(300, 1200);
      tick();
    }
    const stop = () => {
      running = false;
      cancelAnimationFrame(frame);
      clearTimeout(timer);
    };

    readColors();
    resize();
    start();

    const resizeObserver = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(resize);
    resizeObserver?.observe(host);
    const viewObserver = typeof IntersectionObserver === "undefined"
      ? null
      : new IntersectionObserver(([entry]) => {
          visible = !!entry?.isIntersecting;
          if (visible) start();
          else stop();
        });
    viewObserver?.observe(host);
    const onVisibility = () => (document.hidden ? stop() : start());
    document.addEventListener("visibilitychange", onVisibility);
    // Theme switches change the colours the canvas reads.
    const themeObserver = new MutationObserver(() => {
      readColors();
      if (!running) draw(0);
    });
    themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme"] });

    return () => {
      stop();
      resizeObserver?.disconnect();
      viewObserver?.disconnect();
      themeObserver.disconnect();
      document.removeEventListener("visibilitychange", onVisibility);
    };
  }, [tone, color, density]);

  const local = (event: PointerEvent<HTMLDivElement>) => {
    const rect = event.currentTarget.getBoundingClientRect();
    return { x: event.clientX - rect.left, y: event.clientY - rect.top };
  };

  return (
    <div
      ref={root}
      className={cn("relative isolate overflow-hidden bg-background text-foreground", tone === "dark" && "dark", className)}
      style={tone === "light" ? PAPER : tone === "dark" ? { colorScheme: "dark" } : undefined}
      onPointerDown={(event) => {
        if (!interactive) return;
        if ((event.target as HTMLElement).closest("a,button,input,select,textarea,label,[role=button],[tabindex]")) return;
        const { x, y } = local(event);
        fire.current(x, y);
      }}
      onPointerMove={(event) => {
        if (!constellation) return;
        pointer.current = { ...local(event), active: true };
      }}
      onPointerLeave={() => {
        pointer.current.active = false;
      }}
    >
      <canvas ref={canvas} aria-hidden="true" className="pointer-events-none absolute inset-0 -z-20 size-full" />
      <div
        aria-hidden="true"
        className="pointer-events-none absolute inset-0 -z-10"
        style={{
          background:
            "radial-gradient(80% 60% at 18% 0%, color-mix(in oklab, var(--chart-2) 16%, transparent), transparent 70%), radial-gradient(70% 55% at 90% 100%, color-mix(in oklab, var(--chart-4) 14%, transparent), transparent 70%)",
        }}
      />
      {children !== undefined && <div className="relative z-10">{children}</div>}
    </div>
  );
}