Galaxy background
The starfield behind joinstarlight.com's home page: real-coloured stars cruising slowly forward, twinkling and flaring over a faint violet haze.
Build a React 19 + TypeScript component called GalaxyBackground: a realistic, slowly cruising 3D starfield on a canvas, the kind you'd run full-screen behind a landing page. Constraints - One .tsx file, "use client", imports from react only. CSS in a template string rendered as <style href="ui-interstellar-space" precedence="ui">, classes prefixed "gb-". - The root fills its parent (position relative, width/height 100%, overflow hidden, isolation isolate) and paints a background prop, default #0a0a0f. Size the canvas with a ResizeObserver on the root, never the window, and cap devicePixelRatio at 1.5. Map the pointer relative to the root. Props and defaults - pointer "lean" | "off" (default "lean"), and multipliers speed, density, twinkle, glow, haze, all default 1. Keep them in a ref read every frame so they apply without restarting the field; repopulate the stars only when density changes. Stars - Count = clamp(width × height × 950 / (1920 × 1080) × density, 120 × density, 1600). Each star has x, y in [−w/2, w/2] × [−h/2, h/2] and z in (0, 1000]. Project with sx = x / z × 1000 + vanishingX (same for y), so the back of the field spans the frame at any size. Each frame move z toward 0 by 0.015 × 16 × speed; respawn at z = 1000 when z ≤ 0 or the star leaves the frame by 60px. - Colour by stellar temperature, weighted: blue 155,176,255 (5%), blue-white 190,207,255 (9%), 228,234,255 (13%), white (28%), warm white 255,248,240 (18%), sun-like 255,240,214 (14%), orange 255,220,178 (9%), deep orange 255,198,158 (4%). - Magnitude: 2% of stars get 0.85–1, the rest Math.random()³. With nearness t = 1 − z / 1000: core radius = (0.38 + t × 1.5) × (0.45 + mag × 1.05); alpha = (0.18 + t × 0.72) × (0.32 + mag × 0.78) × twinkle. - Draw with globalCompositeOperation "lighter": a pre-rendered 128px radial glow sprite per colour (stops 0.85 / 0.45 / 0.14 / 0.03 / 0 at 0 / 6% / 16% / 40% / 100%) at radius core × (2.6 + mag × 3.6) × glow and alpha × (0.4 + mag × 0.45); then a crisp arc for the core; a white-hot centre (core × 0.55) on stars brighter than 0.5; and a soft four-point diffraction spike sprite, radius core × (7 + mag × 12), on stars brighter than 0.82. - Twinkle: two sines summed (0.62 and 0.38 weights) with random frequencies 0.003–0.009 per ms and 1.8–3.1× that, depth (0.14 + (1 − mag) × 0.66) × random 0.4–1 × the twinkle prop, floored at 0.04, so faint stars wink and bright ones hold. Stars brighter than 0.55 also flash red, green and blue out of phase by up to (mag − 0.55) × 95 rgb units. Haze and drift - A faint nebula: four large radial gradients (46,64,120 / 74,48,116 / 30,72,96 / 58,44,104, at 5% alpha in the centre) added together on an offscreen canvas once per resize, painted at 50% × haze opacity, 48px oversized, offset by the drift × 24 for parallax. - Drift eases (0.03 per frame) toward a constant 0.1 downward, plus the pointer lean; each star slides by drift × nearness × 2 × speed per frame. - With pointer "lean", the vanishing point leans toward the pointer by up to 2.5% of the frame, eased at 0.03 per frame, and back to centre on pointerleave. Be a good guest - Render nothing until requestIdleCallback (1.5s timeout), then fade the canvas in over 0.8s. - Pause the loop with an IntersectionObserver when off screen and on visibilitychange; clear everything on unmount. Canvas aria-hidden. - prefers-reduced-motion: draw one still frame with no twinkle, and redraw it when props change.
"use client";
/**
* GalaxyBackground — the starfield behind joinstarlight.com's home page.
*
* From Starlight (joinstarlight.com), where it runs full-screen behind the landing page at the settings used as
* the defaults here. On the site its vanishing point also swings as you scroll the page; here it fills its parent
* and drifts on its own instead, so it works anywhere. (The "Warp drive button" on this page is the same field
* with the sign-up jump to hyperspace.)
*
* How it works
* - A 2D canvas draws ~1 star per 2,200px² in 3D: each star has x/y/z and is projected toward a vanishing
* point, cruising slowly forward; when it passes the camera it respawns at the back.
* - Stars look real rather than gamey: colours follow stellar temperatures (mostly white and warm white, a few
* blue and orange), brightness follows a steep power law (many faint, ~2% bright anchors), and every star is
* a crisp core plus a soft pre-rendered glow, added with "lighter" so light stacks like light.
* - Twinkle is two summed oscillators per star, so it never ticks like a metronome. Faint stars wink, bright
* ones hold steady but flash colour (chromatic scintillation) and get four-point diffraction spikes.
* - Behind the stars, a barely-there blue and violet haze, drawn once offscreen and moved with slight parallax.
* - The vanishing point leans a little toward the pointer, as if the camera banks.
* - It fades in on the first idle moment, pauses off screen and in hidden tabs, and with reduced motion draws
* one still frame (redrawn when props change).
*
* Usage
* <div style={{ height: 520 }}>
* <GalaxyBackground />
* </div>
* <GalaxyBackground speed={3} density={1.5} haze={2} pointer="off" />
*
* Requirements: React 19 (for the hoisted <style>). No other dependencies.
*/
import { useEffect, useRef } from "react";
type Pointer = "lean" | "off";
type GalaxyBackgroundProps = {
/** "lean" tilts the vanishing point toward the pointer; "off" ignores it. */
pointer?: Pointer;
/** Cruise speed through the field, as a multiple of the site's. 0 holds still (the stars still twinkle). */
speed?: number;
/** Stars per area, as a multiple of the site's. */
density?: number;
/** How deep the twinkle and colour flashing go, as a multiple of the site's. 0 is steady light. */
twinkle?: number;
/** Strength of the blue and violet haze behind the stars. 0 is a clean black sky. */
haze?: number;
/** Size of the soft halo around each star. 0 leaves only the pinpoints. */
glow?: number;
/** The sky behind the stars. */
background?: string;
};
// ── Motion ──────────────────────────────────────────────────────────────────────────────────────
const BASE_SPEED = 0.015; // the idle cruise, as if drifting through space
const MAX_DEPTH = 1000;
const STAR_DENSITY = 950 / (1920 * 1080); // ~950 stars on a 1080p screen
const MAX_STARS = 1600;
// ── Colour ──────────────────────────────────────────────────────────────────────────────────────
type Rgb = readonly [number, number, number];
// Stellar colour temperatures, weighted toward white and warm white like the real night sky.
const STAR_COLORS: { rgb: Rgb; str: string; weight: number }[] = [
{ rgb: [155, 176, 255], str: "155,176,255", weight: 0.05 }, // O/B blue
{ rgb: [190, 207, 255], str: "190,207,255", weight: 0.09 }, // A blue-white
{ rgb: [228, 234, 255], str: "228,234,255", weight: 0.13 }, // late A / early F
{ rgb: [255, 255, 255], str: "255,255,255", weight: 0.28 }, // white
{ rgb: [255, 248, 240], str: "255,248,240", weight: 0.18 }, // F warm white
{ rgb: [255, 240, 214], str: "255,240,214", weight: 0.14 }, // G, sun-like
{ rgb: [255, 220, 178], str: "255,220,178", weight: 0.09 }, // K orange
{ rgb: [255, 198, 158], str: "255,198,158", weight: 0.04 }, // M deep orange
];
const STAR_CDF = (() => {
let acc = 0;
return STAR_COLORS.map((c) => (acc += c.weight));
})();
function pickColor() {
const r = Math.random() * STAR_CDF[STAR_CDF.length - 1];
return STAR_COLORS[STAR_CDF.findIndex((edge) => r <= edge)] ?? STAR_COLORS[STAR_COLORS.length - 1];
}
type Star = {
x: number;
y: number;
z: number;
rgb: Rgb;
sprite: HTMLCanvasElement;
mag: number; // 0–1 brightness
twAmp: number; // twinkle depth: faint stars wink, bright ones hold steady
f1: number;
f2: number;
ph1: number;
ph2: number;
chroma: number; // colour flashing, bright stars only
cf: number;
cph: number;
};
/** The soft halo around a star, one per colour. The sharp core is drawn separately so stars stay crisp. */
function makeGlowSprite(color: string) {
const size = 128;
const c = document.createElement("canvas");
c.width = c.height = size;
const g = c.getContext("2d")!;
const r = size / 2;
const grad = g.createRadialGradient(r, r, 0, r, r, r);
grad.addColorStop(0, `rgba(${color},0.85)`);
grad.addColorStop(0.06, `rgba(${color},0.45)`);
grad.addColorStop(0.16, `rgba(${color},0.14)`);
grad.addColorStop(0.4, `rgba(${color},0.03)`);
grad.addColorStop(1, `rgba(${color},0)`);
g.fillStyle = grad;
g.fillRect(0, 0, size, size);
return c;
}
/** A soft four-point diffraction spike for the brightest stars. */
function makeSpikeSprite() {
const size = 128;
const c = document.createElement("canvas");
c.width = c.height = size;
const g = c.getContext("2d")!;
const mid = size / 2;
for (const horizontal of [true, false]) {
const grad = horizontal ? g.createLinearGradient(0, mid, size, mid) : g.createLinearGradient(mid, 0, mid, size);
grad.addColorStop(0, "rgba(255,255,255,0)");
grad.addColorStop(0.4, "rgba(255,255,255,0.5)");
grad.addColorStop(0.5, "rgba(255,255,255,1)");
grad.addColorStop(0.6, "rgba(255,255,255,0.5)");
grad.addColorStop(1, "rgba(255,255,255,0)");
g.fillStyle = grad;
if (horizontal) g.fillRect(0, mid - 0.6, size, 1.2);
else g.fillRect(mid - 0.6, 0, 1.2, size);
}
return c;
}
type Settings = Required<Omit<GalaxyBackgroundProps, "background">>;
export default function GalaxyBackground({
pointer = "lean",
speed = 1,
density = 1,
twinkle = 1,
haze = 1,
glow = 1,
background = "#0a0a0f",
}: GalaxyBackgroundProps) {
const rootRef = useRef<HTMLDivElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
// Read every frame, so the props apply without restarting the field.
const settings = useRef<Settings>({ pointer, speed, density, twinkle, haze, glow });
const redraw = useRef<() => void>(() => {});
useEffect(() => {
settings.current = { pointer, speed, density, twinkle, haze, glow };
redraw.current();
}, [pointer, speed, density, twinkle, haze, glow]);
useEffect(() => {
const root = rootRef.current;
const canvas = canvasRef.current;
const ctx = canvas?.getContext("2d", { alpha: true });
if (!root || !canvas || !ctx) return;
const still = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
let w = 0;
let h = 0;
let raf = 0;
let onScreen = true;
let started = false;
let populatedDensity = -1;
// A slow downward drift plus a gentle lean toward the pointer.
let driftX = 0;
let driftY = 0;
let lookX = 0;
let lookY = 0;
let targetLookX = 0;
let targetLookY = 0;
const stars: Star[] = [];
const glowSprites = new Map(STAR_COLORS.map((c) => [c.str, makeGlowSprite(c.str)]));
const spike = makeSpikeSprite();
let nebula: HTMLCanvasElement | null = null;
// A barely-there deep-space haze, for depth.
const buildNebula = () => {
const c = document.createElement("canvas");
c.width = Math.max(2, Math.ceil(w));
c.height = Math.max(2, Math.ceil(h));
const g = c.getContext("2d")!;
g.globalCompositeOperation = "lighter";
const diag = Math.hypot(w, h);
for (const [x, y, r, col] of [
[0.22, 0.32, 0.55, "46,64,120"],
[0.78, 0.6, 0.6, "74,48,116"],
[0.55, 0.18, 0.45, "30,72,96"],
[0.4, 0.82, 0.5, "58,44,104"],
] as const) {
const grad = g.createRadialGradient(x * w, y * h, 0, x * w, y * h, r * diag * 0.5);
grad.addColorStop(0, `rgba(${col},0.05)`);
grad.addColorStop(0.5, `rgba(${col},0.018)`);
grad.addColorStop(1, `rgba(${col},0)`);
g.fillStyle = grad;
g.fillRect(0, 0, w, h);
}
nebula = c;
};
const resetStar = (s: Star) => {
s.x = (Math.random() - 0.5) * w;
s.y = (Math.random() - 0.5) * h;
s.z = MAX_DEPTH;
// Overwhelmingly faint, with ~2% bright anchors so the sky always has a few prominent points.
const mag = Math.random() < 0.02 ? 0.85 + Math.random() * 0.15 : Math.pow(Math.random(), 3);
s.mag = mag;
const col = pickColor();
s.rgb = col.rgb;
s.sprite = glowSprites.get(col.str)!;
s.twAmp = (0.14 + (1 - mag) * 0.66) * (0.4 + Math.random() * 0.6);
s.f1 = 0.003 + Math.random() * 0.006; // ~1–3.5s flicker
s.f2 = s.f1 * (1.8 + Math.random() * 1.3); // a faster second one breaks the sine
s.ph1 = Math.random() * Math.PI * 2;
s.ph2 = Math.random() * Math.PI * 2;
s.chroma = mag > 0.55 ? (mag - 0.55) * 95 * (0.5 + Math.random() * 0.5) : 0;
s.cf = 0.0018 + Math.random() * 0.004;
s.cph = Math.random() * Math.PI * 2;
};
const populate = () => {
const d = settings.current.density;
const count = Math.min(MAX_STARS, Math.max(Math.round(120 * d), Math.floor(w * h * STAR_DENSITY * d)));
stars.length = 0;
for (let i = 0; i < count; i++) {
const s = {} as Star;
resetStar(s);
s.z = Math.random() * MAX_DEPTH;
stars.push(s);
}
populatedDensity = d;
};
const draw = (now: number) => {
const set = settings.current;
if (set.density !== populatedDensity) populate();
ctx.clearRect(0, 0, w, h);
// The lean eases in slowly; it rides alongside a steady drift downward.
const lean = set.pointer === "lean" && !still;
lookX += ((lean ? targetLookX : 0) - lookX) * 0.03;
lookY += ((lean ? targetLookY : 0) - lookY) * 0.03;
driftX += (lookX * 0.16 - driftX) * 0.03;
driftY += (0.1 + lookY * 0.11 - driftY) * 0.03;
// Drawn slightly oversized so the parallax never exposes an edge.
if (nebula && set.haze > 0) {
ctx.globalAlpha = Math.min(1, 0.5 * set.haze);
ctx.drawImage(nebula, driftX * 24 - 24, driftY * 24 - 24, w + 48, h + 48);
ctx.globalAlpha = 1;
}
const motion = still ? 0 : set.speed;
const step = BASE_SPEED * 16 * motion;
const tw = still ? 0 : set.twinkle;
const vx = w / 2 + lookX * w * 0.025;
const vy = h / 2 + lookY * h * 0.025;
ctx.globalCompositeOperation = "lighter"; // light adds, like photons
for (const s of stars) {
s.z -= step;
s.x += driftX * (1 - s.z / MAX_DEPTH) * 2 * motion;
s.y += driftY * (1 - s.z / MAX_DEPTH) * 2 * motion;
if (s.z <= 0) {
resetStar(s);
continue;
}
// Focal length = MAX_DEPTH, so the back of the field spans exactly the frame at any size.
const sx = (s.x / s.z) * MAX_DEPTH + vx;
const sy = (s.y / s.z) * MAX_DEPTH + vy;
if (sx < -60 || sx > w + 60 || sy < -60 || sy > h + 60) {
resetStar(s);
continue;
}
const t = 1 - s.z / MAX_DEPTH; // 0 far, 1 near
let flicker = 1;
if (tw > 0) {
const f = Math.sin(now * s.f1 + s.ph1) * 0.62 + Math.sin(now * s.f2 + s.ph2) * 0.38;
flicker = Math.max(0.04, 1 + f * Math.min(1.2, s.twAmp * tw));
}
// A real star is a near-perfect point: a tiny razor-sharp core, never a blob.
const coreR = (0.38 + t * 1.5) * (0.45 + s.mag * 1.05);
const alpha = Math.min(1, (0.18 + t * 0.72) * (0.32 + s.mag * 0.78) * flicker);
let r = s.rgb[0];
let g = s.rgb[1];
let b = s.rgb[2];
if (s.chroma > 0 && tw > 0) {
// Bright stars flash red, green and blue out of phase, as the air splits their light.
const cf = s.chroma * tw;
r += Math.sin(now * s.cf + s.cph) * cf;
g += Math.sin(now * s.cf * 1.3 + s.cph + 2.1) * cf * 0.55;
b += Math.sin(now * s.cf + s.cph + Math.PI) * cf;
}
const col = `${Math.max(0, Math.min(255, r | 0))},${Math.max(0, Math.min(255, g | 0))},${Math.max(0, Math.min(255, b | 0))}`;
if (set.glow > 0) {
const bloom = coreR * (2.6 + s.mag * 3.6) * set.glow;
ctx.globalAlpha = Math.min(1, alpha * (0.4 + s.mag * 0.45));
ctx.drawImage(s.sprite, sx - bloom, sy - bloom, bloom * 2, bloom * 2);
}
ctx.globalAlpha = alpha;
ctx.fillStyle = `rgb(${col})`;
ctx.beginPath();
ctx.arc(sx, sy, coreR, 0, Math.PI * 2);
ctx.fill();
if (s.mag > 0.5) {
// A white-hot centre on bright stars, colour left in the halo.
ctx.globalAlpha = alpha * (s.mag - 0.5) * 1.6;
ctx.fillStyle = "#fff";
ctx.beginPath();
ctx.arc(sx, sy, coreR * 0.55, 0, Math.PI * 2);
ctx.fill();
}
if (s.mag > 0.82 && set.glow > 0) {
const len = coreR * (7 + s.mag * 12) * Math.min(1.5, set.glow);
ctx.globalAlpha = alpha * 0.4 * s.mag;
ctx.drawImage(spike, sx - len, sy - len, len * 2, len * 2);
}
ctx.globalAlpha = 1;
}
ctx.globalCompositeOperation = "source-over";
};
const loop = (now: number) => {
draw(now);
raf = requestAnimationFrame(loop);
};
const run = () => {
if (started && !raf && !still && onScreen && document.visibilityState === "visible") {
raf = requestAnimationFrame(loop);
}
};
const stop = () => {
cancelAnimationFrame(raf);
raf = 0;
};
const resize = () => {
const r = root.getBoundingClientRect();
if (r.width === 0 || r.height === 0) return;
// 1.5 is indistinguishable for 1–2px stars and halves the fill cost.
const dpr = Math.min(window.devicePixelRatio || 1, 1.5);
w = r.width;
h = r.height;
canvas.width = Math.floor(w * dpr);
canvas.height = Math.floor(h * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
buildNebula();
populate();
if (started && still) draw(performance.now());
};
const onPointerMove = (e: PointerEvent) => {
const r = root.getBoundingClientRect();
targetLookX = ((e.clientX - r.left) / r.width) * 2 - 1;
targetLookY = ((e.clientY - r.top) / r.height) * 2 - 1;
};
const onPointerLeave = () => {
targetLookX = 0;
targetLookY = 0;
};
const onVisibility = () => (document.visibilityState === "visible" ? run() : stop());
// As on the site, nothing renders until the browser is idle, then the canvas fades in.
const start = () => {
started = true;
canvas.style.opacity = "1";
if (still) draw(performance.now());
run();
};
const idle = "requestIdleCallback" in window ? window.requestIdleCallback(start, { timeout: 1500 }) : 0;
const idleTimer = idle ? undefined : setTimeout(start, 300);
redraw.current = () => {
if (started && still) draw(performance.now());
};
resize();
const ro = new ResizeObserver(resize);
ro.observe(root);
const io = new IntersectionObserver(([entry]) => {
onScreen = entry.isIntersecting;
if (onScreen) run();
else stop();
});
io.observe(root);
root.addEventListener("pointermove", onPointerMove, { passive: true });
root.addEventListener("pointerleave", onPointerLeave);
root.addEventListener("pointercancel", onPointerLeave);
document.addEventListener("visibilitychange", onVisibility);
return () => {
stop();
if (idle) window.cancelIdleCallback(idle);
if (idleTimer) clearTimeout(idleTimer);
redraw.current = () => {};
ro.disconnect();
io.disconnect();
root.removeEventListener("pointermove", onPointerMove);
root.removeEventListener("pointerleave", onPointerLeave);
root.removeEventListener("pointercancel", onPointerLeave);
document.removeEventListener("visibilitychange", onVisibility);
};
}, []);
return (
<div ref={rootRef} className="gb" style={{ background }}>
<style href="ui-interstellar-space" precedence="ui">
{css}
</style>
<canvas ref={canvasRef} className="gb-canvas" aria-hidden="true" />
</div>
);
}
const css = `
.gb {
position: relative;
width: 100%;
height: 100%;
overflow: hidden;
isolation: isolate;
}
.gb-canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
opacity: 0;
transition: opacity 0.8s ease;
}
@media (prefers-reduced-motion: reduce) {
.gb-canvas { transition: none; }
}
`;
