Galaxy Drift
Fly through the stars toward the Milky Way. A real photograph of the galaxy band hangs at infinity behind a true 3D volume of stars: you cruise slowly forward, near stars streaming past bigger and faster while far ones barely move, under a fine grain of distant stars that twinkle over the galaxy. It moves like space, not like a spring: scrolling is thrust, so keep scrolling and you keep flying deeper, the stars streaking with your speed; stop and you coast, easing back to a slow cruise, and scroll back to fly backward. The cursor steers your view so every star shifts by its real depth, and it is a telescope that magnifies and exposes the sky deeper. A click is a warp burst with a spray of shooting stars, and on load you arrive at speed and slow to a cruise.
Tweak
LIVELIVESky
Flight
Interactive
Scroll to fly, steer with the cursor, click to warp
Usage
Follows your tweaks.
import { GalaxyDrift } from "@/components/inreact/galaxy-drift";
export function Hero() {
return (
<GalaxyDrift
className="h-screen w-full"
>
{/* optional: your hero content, drawn above the sky */}
</GalaxyDrift>
);
}Install with the CLI
npx shadcn@latest add https://inreact.vercel.app/r/galaxy-drift.jsonOr copy the source
Install the dependencies, then save this as components/inreact/galaxy-drift.tsx.
npm install gsap"use client";
import { gsap } from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { useEffect, useRef, type ReactNode } from "react";
gsap.registerPlugin(ScrollTrigger);
/**
* Galaxy Drift: fly through the stars toward the Milky Way.
*
* A real photograph of the galaxy band hangs at infinity behind a true 3D
* volume of stars. You cruise slowly forward through it: near stars stream
* past, bigger and faster, while far ones barely move, and a fine grain of
* distant stars twinkles over the galaxy. Shooting stars cross now and then.
*
* It moves like space, not like a spring: scrolling is thrust. Keep scrolling
* and you keep flying deeper, the stars streaking with your speed; stop and you
* coast, easing back to a slow cruise. Scroll back to fly backward. The cursor
* steers your view, so every star shifts by its real depth, and it is a
* telescope: under it the sky is gently magnified and exposed deeper. A click
* is a warp burst of speed with a spray of shooting stars; on load you arrive
* at speed and slow to a cruise.
*
* <GalaxyDrift className="h-screen w-full">
* <YourHero />
* </GalaxyDrift>
*
* Bring your own sky with `image` (a star-free galaxy photo works best).
* WebGL2, real bloom (1/4 and 1/16 size). Pauses off-screen; reduced motion
* shows a still frame; the plain photo without WebGL2.
*/
export interface GalaxyDriftProps {
/** The galaxy photo, at infinity behind the stars. */
image?: string;
/** How many stars, 0 to 2. */
stars?: number;
/** How much the distant stars twinkle. */
twinkle?: number;
/** Speed of the slow idle cruise through the stars. */
cruise?: number;
/** How hard scrolling thrusts you forward. */
thrust?: number;
/** How often shooting stars cross the sky, per minute (0 for none). */
meteors?: number;
/** Strength of the telescope under the cursor. */
telescope?: number;
/** Brightness of the galaxy band. */
exposure?: number;
/** Strength of the bloom on the stars. */
glow?: number;
/** Background shown while the photo loads. */
background?: string;
/** Steering, telescope, click warp, scroll flight. */
interactive?: boolean;
/** Scroll container if the page does not scroll the window. */
scroller?: Element | null;
/** Foreground content, drawn above the sky. */
children?: ReactNode;
className?: string;
}
const MAXM = 6; // meteors in flight at once
const MAXW = 3; // starlight pulses
const NL = 12; // depth layers of flying stars
const QUAD = `#version 300 es
in vec2 aQ; out vec2 vUv;
void main(){ vUv = aQ * 0.5 + 0.5; gl_Position = vec4(aQ, 0.0, 1.0); }`;
const SCENE = `#version 300 es
precision highp float;
uniform sampler2D uImg;
uniform vec2 uRes, uImgSize, uMouse, uLook; // css px; uLook = where you are looking, -1..1
uniform float uDpr, uScale, uTime, uTravel, uSpeed, uGalZoom, uHover, uStars, uTwinkle, uTele, uExpo, uIntro, uFlash;
uniform vec4 uMet[${MAXM}]; // x, y (css px), angle, start time
uniform vec4 uWave[${MAXW}];
in vec2 vUv;
out vec4 o;
float h21(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
vec2 h22(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * vec3(0.1031, 0.1030, 0.0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
float noise(vec2 p) {
vec2 i = floor(p), f = fract(p);
f = f * f * (3.0 - 2.0 * f);
return mix(mix(h21(i), h21(i + vec2(1, 0)), f.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), f.x), f.y);
}
vec3 starTint(float t) { return mix(vec3(1.0), mix(vec3(1.0, 0.82, 0.66), vec3(0.72, 0.84, 1.0), t), 0.6); }
void main() {
vec2 p = vec2(gl_FragCoord.x, uRes.y * uDpr - gl_FragCoord.y) / uDpr;
float minD = min(uRes.x, uRes.y);
vec2 cen = uRes * 0.5;
// the telescope: under the cursor the sky is gently magnified and exposed deeper
vec2 dm = p - uMouse;
float tel = exp(-dot(dm, dm) / (0.035 * minD * minD)) * uHover * uTele;
vec2 pl = p - dm * tel * 0.22;
vec2 q = (pl - cen) / minD; // view direction, minD units
// ---- the galaxy, at infinity: it only turns with your view and grows very slowly as you travel ----
// flying takes you into the galaxy forever: two scales of it, one zoom step apart, cross-faded
vec2 qv = (q + uLook * 0.03) * minD;
float gf = fract(uGalZoom);
float zA = pow(1.8, gf), zB = pow(1.8, gf - 1.0);
vec2 qa = qv / zA, qb = qv / zB;
float wB = smoothstep(0.0, 1.0, gf);
vec3 gal = mix(textureLod(uImg, qa / uScale / uImgSize + 0.5, 0.0).rgb, textureLod(uImg, qb / uScale / uImgSize + 0.5, 0.0).rgb, wB);
vec2 qg = qv;
float glum = dot(mix(textureLod(uImg, qa / uScale / uImgSize + 0.5, 4.0).rgb, textureLod(uImg, qb / uScale / uImgSize + 0.5, 4.0).rgb, wB), vec3(0.33));
float dust = noise(qg / 2.2) * 0.6 + noise(qg / 0.9 + 7.0) * 0.4;
gal *= (0.82 + 0.36 * dust) * uExpo * 0.85 * (1.0 + tel * 0.8);
gal = mix(vec3(dot(gal, vec3(0.33))), gal, 1.0 + tel * 0.35);
// starlight pulses from clicks make the stars flare as they pass
float pulse = 0.0;
for (int i = 0; i < ${MAXW}; i++) {
vec4 W = uWave[i];
if (W.w <= 0.0) continue;
float age = uTime - W.z;
if (age < 0.0 || age > 3.0) continue;
float rr = length(p - W.xy) / minD;
float fr = rr - age * 0.6;
pulse += exp(-fr * fr / 0.006) * exp(-age * 1.1) * W.w;
}
// ---- distant stars: a fine grain at near-infinity, densest along the band, twinkling ----
vec3 st = vec3(0.0);
{
vec2 g = (qg + uLook * 4.0) / 3.0;
vec2 id = floor(g);
float hh = h21(id + 1.0);
float dens = 0.62 * mix(0.45, 1.6, smoothstep(0.02, 0.22, glum)) * uStars * (1.0 + tel * 0.9);
if (hh < dens) {
vec2 d = (g - id - 0.2 - 0.6 * h22(id + 1.7)) * 3.0;
float mag = pow(h21(id + 4.3), 4.5);
float r = (0.38 + 0.8 * mag) / uDpr + 0.18;
float tw = 1.0 + uTwinkle * 0.45 * sin(uTime * (1.3 + 3.0 * h21(id + 9.1)) + h21(id + 4.7) * 6.2831) * smoothstep(0.1, 0.5, mag + 0.2);
st += starTint(h21(id + 8.7)) * exp(-dot(d, d) / (r * r)) * (0.2 + 1.8 * mag) * 0.5 * tw;
}
}
// ---- the star volume you fly through: layers at true depths, projected in perspective ----
// depth z runs from 1 (far) to 0 (passing you); a star at world position w appears at (w - look) / z
float streakK = uSpeed * 0.16;
for (int i = 0; i < ${NL}; i++) {
float li = float(i);
float ph = li / ${NL}.0 + uTravel;
float wrapN = floor(ph);
float z = 1.0 - fract(ph);
z = max(z, 0.015);
// the world under this pixel at this depth (steering shifts near stars more: parallax)
vec2 w = (q * z + uLook * 0.08) * 10.0;
vec2 id = floor(w);
vec2 seed = id + vec2(wrapN * 17.31 + li * 3.7, wrapN * 5.13 - li * 1.9);
float hh = h21(seed);
if (hh > 0.6 * uStars) continue;
vec2 off = 0.15 + 0.7 * h22(seed + 2.3);
vec2 dCell = (w - id - off); // cell units
vec2 d = dCell / 10.0 / z * minD; // css px on screen
// motion streak: stars stretch along their flight away from the centre of view
vec2 sp = (id + off) / 10.0 - uLook * 0.08; // where the star sits in view space * z
vec2 rd = normalize(sp + 1e-4);
float len = streakK / z * minD * 0.05;
float along = dot(d, rd);
d -= rd * clamp(along, -len, len * 0.3);
float mag = pow(h21(seed + 4.1), 3.0);
float r = clamp(0.4 / uDpr + 0.2 / z * (0.4 + mag), 0.35, 2.2);
float core = exp(-dot(d, d) / (r * r));
// far ones fade in out of the dark; near ones flare past and are gone
float fade = smoothstep(1.0, 0.72, z) * smoothstep(0.015, 0.09, z);
float bright = (0.5 + 1.6 * mag) * clamp(0.32 / z, 0.4, 2.2) * fade;
st += starTint(h21(seed + 6.6)) * core * bright;
}
// the brightest stars appear first on load, the faint ones after
float lumS = max(st.r, max(st.g, st.b));
st *= smoothstep(0.0, 0.5, uIntro + lumS * 0.4 - 0.15) * 0.8 * (1.0 + pulse * 2.5);
vec3 col = gal * smoothstep(0.25, 1.0, uIntro) + st;
// shooting stars: a bright head and a long fading tail
for (int i = 0; i < ${MAXM}; i++) {
vec4 M = uMet[i];
if (M.w < 0.0) continue;
float age = uTime - M.w;
if (age < 0.0 || age > 1.2) continue;
vec2 dir = vec2(cos(M.z), sin(M.z));
vec2 head = M.xy + dir * minD * 1.25 * age;
float tail = minD * 0.28 * smoothstep(0.0, 0.25, age);
vec2 rel = p - head;
float alongM = -dot(rel, dir);
float side = length(rel + dir * alongM);
if (alongM < -4.0 || alongM > tail) continue;
float t01 = clamp(alongM / max(tail, 1.0), 0.0, 1.0);
float width = mix(1.5, 0.5, t01);
float life = smoothstep(0.0, 0.08, age) * smoothstep(1.2, 0.7, age);
float k = exp(-side * side / (width * width)) * (1.0 - t01) * (1.0 - t01) * life;
k += exp(-dot(rel, rel) / 2.2) * life * 0.9;
col += mix(vec3(0.85, 0.92, 1.0), vec3(1.0, 0.78, 0.55), t01) * k * 1.6;
}
col += vec3(0.75, 0.85, 1.0) * pulse * 0.025 + vec3(0.8, 0.88, 1.0) * uFlash * 0.015 * tel;
o = vec4(col, 1.0);
}`;
const BLUR = `#version 300 es
precision mediump float;
uniform sampler2D uTex; uniform vec2 uStep; in vec2 vUv; out vec4 o;
void main() {
vec4 c = texture(uTex, vUv) * 0.2270;
c += (texture(uTex, vUv + uStep * 1.3846) + texture(uTex, vUv - uStep * 1.3846)) * 0.3162;
c += (texture(uTex, vUv + uStep * 3.2308) + texture(uTex, vUv - uStep * 3.2308)) * 0.0703;
o = c;
}`;
const BRIGHT = `#version 300 es
precision mediump float;
uniform sampler2D uTex; in vec2 vUv; out vec4 o;
void main() {
vec3 c = texture(uTex, vUv).rgb;
float l = max(c.r, max(c.g, c.b));
o = vec4(c * smoothstep(0.45, 1.0, l), 1.0);
}`;
const COMPOSITE = `#version 300 es
precision highp float;
uniform sampler2D uScene, uBloom, uWide;
uniform float uGlow;
in vec2 vUv; out vec4 o;
float h(vec2 p) { vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
void main() {
vec3 sc = texture(uScene, vUv).rgb;
vec3 bl = texture(uBloom, vUv).rgb * 0.8 + texture(uWide, vUv).rgb * 0.25;
vec3 x = sc + bl * uGlow;
vec3 col = x / (1.0 + max(x - 0.85, 0.0) * 0.9);
col += (h(gl_FragCoord.xy) + h(gl_FragCoord.yx + 17.0) - 1.0) / 255.0;
o = vec4(clamp(col, 0.0, 1.0), 1.0);
}`;
const isReducedMotion = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
export function GalaxyDrift({
image = "/backgrounds/galaxy-drift/galaxy.jpg",
stars = 1,
twinkle = 1,
cruise = 1,
thrust = 1,
meteors = 6,
telescope = 1,
exposure = 1,
glow = 0.6,
background = "#030304",
interactive = true,
scroller,
children,
className,
}: GalaxyDriftProps) {
const hostRef = useRef<HTMLDivElement>(null);
const props = useRef({ stars, twinkle, cruise, thrust, meteors, telescope, exposure, glow, interactive });
const redraw = useRef<(() => void) | null>(null);
useEffect(() => {
props.current = { stars, twinkle, cruise, thrust, meteors, telescope, exposure, glow, interactive };
redraw.current?.();
}, [stars, twinkle, cruise, thrust, meteors, telescope, exposure, glow, interactive]);
useEffect(() => {
const host = hostRef.current;
if (!host) return;
if (getComputedStyle(host).position === "static") host.style.position = "relative";
const still = isReducedMotion();
const canvas = document.createElement("canvas");
canvas.setAttribute("aria-hidden", "true");
canvas.style.cssText = "position:absolute;inset:0;width:100%;height:100%;display:block;touch-action:pan-y;opacity:0;transition:opacity .6s ease;";
host.prepend(canvas);
const gl = canvas.getContext("webgl2", { alpha: false, antialias: false, powerPreference: "high-performance" });
if (!gl) {
host.style.backgroundImage = `url(${image})`;
host.style.backgroundSize = "cover";
host.style.backgroundPosition = "center";
canvas.remove();
return;
}
const build = (fs: string) => {
const pr = gl.createProgram()!;
for (const [type, src] of [
[gl.VERTEX_SHADER, QUAD],
[gl.FRAGMENT_SHADER, fs],
] as const) {
const sh = gl.createShader(type)!;
gl.shaderSource(sh, src);
gl.compileShader(sh);
if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) console.error(gl.getShaderInfoLog(sh));
gl.attachShader(pr, sh);
}
gl.bindAttribLocation(pr, 0, "aQ");
gl.linkProgram(pr);
if (!gl.getProgramParameter(pr, gl.LINK_STATUS)) console.error(gl.getProgramInfoLog(pr));
return pr;
};
const sceneProg = build(SCENE);
const blurProg = build(BLUR);
const brightProg = build(BRIGHT);
const compProg = build(COMPOSITE);
const uni = (pr: WebGLProgram, names: string[]) =>
Object.fromEntries(names.map((n) => [n, gl.getUniformLocation(pr, n)])) as Record<string, WebGLUniformLocation | null>;
const US = uni(sceneProg, [
"uImg", "uRes", "uImgSize", "uMouse", "uLook", "uDpr", "uScale", "uTime", "uTravel", "uSpeed", "uGalZoom", "uHover",
"uStars", "uTwinkle", "uTele", "uExpo", "uIntro", "uFlash", "uMet", "uWave",
]);
const UB = uni(blurProg, ["uTex", "uStep"]);
const UR = uni(brightProg, ["uTex"]);
const UC = uni(compProg, ["uScene", "uBloom", "uWide", "uGlow"]);
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
const vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0);
const drawQuad = () => gl.drawArrays(gl.TRIANGLES, 0, 3);
type Target = { fb: WebGLFramebuffer; tex: WebGLTexture; w: number; h: number };
const target = (tw: number, th: number): Target => {
const tex = gl.createTexture()!;
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, tw, th, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
const fb = gl.createFramebuffer()!;
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return { fb, tex, w: tw, h: th };
};
let T: { scene: Target; a: Target; b: Target; c: Target; d: Target } | null = null;
const freeTargets = () => {
if (!T) return;
for (const t of Object.values(T)) {
gl.deleteFramebuffer(t.fb);
gl.deleteTexture(t.tex);
}
T = null;
};
let w = 1, h = 1, dpr = 1, rs = 1;
const resize = () => {
dpr = Math.min(window.devicePixelRatio || 1, 1.5);
w = Math.max(1, host.clientWidth);
h = Math.max(1, host.clientHeight);
canvas.width = Math.round(w * dpr);
canvas.height = Math.round(h * dpr);
const sw = Math.max(1, Math.round(canvas.width * rs)), sh = Math.max(1, Math.round(canvas.height * rs));
freeTargets();
T = {
scene: target(sw, sh),
a: target(Math.max(1, sw >> 2), Math.max(1, sh >> 2)),
b: target(Math.max(1, sw >> 2), Math.max(1, sh >> 2)),
c: target(Math.max(1, sw >> 4), Math.max(1, sh >> 4)),
d: target(Math.max(1, sw >> 4), Math.max(1, sh >> 4)),
};
};
resize();
// ---- flight: pure inertia. thrust adds speed, a gentle drag eases you back to a slow cruise ----
const s = { intro: still ? 1 : 0, mx: -9999, my: -9999, hover: 0, flash: 0 };
let flow = 0;
let travel = still ? 0.37 : 0; // depth travelled, in star layers
let vel = still ? 0 : 2.4; // layers per second; on load you arrive at speed
let distance = 0; // total forward travel, for the galaxy's slow growth
let lookX = 0, lookY = 0, lookTX = 0, lookTY = 0;
const mets: { x: number; y: number; a: number; t: number }[] = [];
const metBuf = new Float32Array(MAXM * 4);
const waves: { x: number; y: number; t: number; s: number }[] = [];
const waveBuf = new Float32Array(MAXW * 4);
let nextMeteor = 3;
const cruiseSpeed = () => 0.045 * Math.max(0, props.current.cruise);
const MAXV = 4;
const imgTex = gl.createTexture()!;
let imgW = 1, imgH = 1, ready = false;
let disposed = false;
const scaleOf = () => Math.max(h / imgH, w / imgW) * 1.04;
const blurPass = (src: Target, dst: Target, dx: number, dy: number) => {
gl.bindFramebuffer(gl.FRAMEBUFFER, dst.fb);
gl.viewport(0, 0, dst.w, dst.h);
gl.useProgram(blurProg);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, src.tex);
gl.uniform1i(UB.uTex, 0);
gl.uniform2f(UB.uStep, dx / src.w, dy / src.h);
drawQuad();
};
const draw = () => {
if (!T || !ready) return;
const p = props.current;
const X = T;
const sceneScale = X.scene.w / canvas.width;
gl.bindFramebuffer(gl.FRAMEBUFFER, X.scene.fb);
gl.viewport(0, 0, X.scene.w, X.scene.h);
gl.useProgram(sceneProg);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, imgTex);
gl.uniform1i(US.uImg, 0);
gl.uniform2f(US.uRes, w, h);
gl.uniform2f(US.uImgSize, imgW, imgH);
gl.uniform2f(US.uMouse, s.mx, s.my);
gl.uniform2f(US.uLook, lookX, lookY);
gl.uniform1f(US.uDpr, dpr * sceneScale);
gl.uniform1f(US.uScale, scaleOf());
gl.uniform1f(US.uTime, flow);
gl.uniform1f(US.uTravel, travel);
gl.uniform1f(US.uSpeed, Math.max(0, Math.abs(vel) - cruiseSpeed()));
// the galaxy is effectively at infinity: it grows only very slowly however far you fly
gl.uniform1f(US.uGalZoom, distance);
gl.uniform1f(US.uHover, s.hover);
gl.uniform1f(US.uStars, Math.max(0, p.stars));
gl.uniform1f(US.uTwinkle, still ? 0 : Math.max(0, p.twinkle));
gl.uniform1f(US.uTele, Math.max(0, p.telescope));
gl.uniform1f(US.uExpo, Math.max(0, p.exposure));
gl.uniform1f(US.uIntro, s.intro);
gl.uniform1f(US.uFlash, s.flash);
metBuf.fill(-1);
mets.forEach((m, i) => metBuf.set([m.x, m.y, m.a, m.t], i * 4));
gl.uniform4fv(US.uMet, metBuf);
waveBuf.fill(0);
waves.forEach((v, i) => waveBuf.set([v.x, v.y, v.t, v.s], i * 4));
gl.uniform4fv(US.uWave, waveBuf);
drawQuad();
gl.bindFramebuffer(gl.FRAMEBUFFER, X.a.fb);
gl.viewport(0, 0, X.a.w, X.a.h);
gl.useProgram(brightProg);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, X.scene.tex);
gl.uniform1i(UR.uTex, 0);
drawQuad();
blurPass(X.a, X.b, 1, 0);
blurPass(X.b, X.a, 0, 1);
blurPass(X.a, X.c, 1, 0);
blurPass(X.c, X.d, 0, 1);
blurPass(X.d, X.c, 1.8, 0);
blurPass(X.c, X.d, 0, 1.8);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.useProgram(compProg);
[X.scene.tex, X.a.tex, X.d.tex].forEach((tex, i) => {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(gl.TEXTURE_2D, tex);
});
gl.uniform1i(UC.uScene, 0);
gl.uniform1i(UC.uBloom, 1);
gl.uniform1i(UC.uWide, 2);
gl.uniform1f(UC.uGlow, Math.max(0, p.glow));
drawQuad();
gl.activeTexture(gl.TEXTURE0);
};
const ro = new ResizeObserver(() => {
resize();
draw();
});
ro.observe(host);
const thrustBy = (dv: number) => {
vel = Math.max(-MAXV, Math.min(MAXV, vel + dv));
};
// a shooting star from a point (or from the top edge), streaking down and across
const meteor = (x?: number, y?: number, angle?: number) => {
const a = angle ?? Math.PI * (0.15 + Math.random() * 0.25) * (Math.random() < 0.5 ? 1 : -1) + (Math.random() < 0.5 ? 0 : Math.PI);
mets.push({ x: x ?? w * (0.1 + Math.random() * 0.8), y: y ?? h * Math.random() * 0.4, a: Math.abs(Math.sin(a)) < 0.2 ? a + 0.4 : a, t: flow });
while (mets.length > MAXM) mets.shift();
};
// ---- cursor: steer your view (every star shifts by its depth) and a telescope ----
const mxTo = gsap.quickTo(s, "mx", { duration: 0.35, ease: "power2.out" });
const myTo = gsap.quickTo(s, "my", { duration: 0.35, ease: "power2.out" });
const hoverTo = gsap.quickTo(s, "hover", { duration: 0.8, ease: "sine.inOut" });
let first = true;
const local = (e: PointerEvent) => {
const r = host.getBoundingClientRect();
return { x: e.clientX - r.left, y: e.clientY - r.top };
};
const move = (e: PointerEvent) => {
if (still || !props.current.interactive) return;
const p = local(e);
if (first) {
gsap.set(s, { mx: p.x, my: p.y });
first = false;
}
mxTo(p.x);
myTo(p.y);
hoverTo(1);
lookTX = (p.x / w) * 2 - 1;
lookTY = (p.y / h) * 2 - 1;
};
const leave = () => {
first = true;
hoverTo(0);
lookTX = 0;
lookTY = 0;
};
// ---- click: a warp burst of speed and a spray of shooting stars ----
const down = (e: PointerEvent) => {
if (still || !props.current.interactive) return;
const p = local(e);
thrustBy(1.6 * Math.max(0, props.current.thrust));
const base = Math.random() * Math.PI * 2;
for (let k = 0; k < 3; k++) meteor(p.x, p.y, base + (k - 1) * (0.5 + Math.random() * 0.3));
waves.push({ x: p.x, y: p.y, t: flow, s: 1 });
while (waves.length > MAXW) waves.shift();
gsap.killTweensOf(s, "flash");
gsap.timeline().to(s, { flash: 1, duration: 0.2, ease: "sine.out" }).to(s, { flash: 0, duration: 1.2, ease: "sine.inOut" });
};
host.addEventListener("pointermove", move);
host.addEventListener("pointerleave", leave);
host.addEventListener("pointerdown", down);
// ---- scroll is thrust: keep scrolling to keep flying deeper; scroll back to fly backward ----
let lastScroll = 0;
let lastST = 0;
const st = still
? null
: ScrollTrigger.create({
trigger: host,
scroller: scroller ?? undefined,
start: "top bottom",
end: "bottom top",
onUpdate: (self) => {
const y = self.scroll();
const dy = y - lastScroll;
lastScroll = y;
lastST = performance.now();
if (!props.current.interactive || Math.abs(dy) > 2000) return;
thrustBy(dy * 0.0016 * Math.max(0, props.current.thrust));
},
});
if (st) lastScroll = st.scroll();
// when the page itself cannot scroll any further (or the stage fills the screen), the wheel still flies you
const wheel = (e: WheelEvent) => {
if (still || !props.current.interactive) return;
if (performance.now() - lastST < 80) return;
const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
thrustBy(Math.max(-200, Math.min(200, dy)) * 0.0016 * Math.max(0, props.current.thrust));
};
host.addEventListener("wheel", wheel, { passive: true });
// ---- loop ----
let visible = true;
let prev = performance.now();
let slow = 0;
let intro: gsap.core.Tween | null = null;
const tick = () => {
const t = performance.now();
const rawDt = (t - prev) / 1000;
const dt = Math.min(0.05, rawDt);
prev = t;
if (!visible || !ready) return;
const p = props.current;
flow += dt;
// space has no springs: you coast, and a gentle drag eases you back to the cruise
const cruiseV = cruiseSpeed();
vel += (cruiseV - vel) * (1 - Math.exp(-dt * 0.7));
travel += vel * dt;
if (travel > 1000 || travel < -1000) travel %= 1;
// the galaxy zooms as you fly: slowly at cruise, fast when you scroll
distance += vel * dt * 0.12;
// the view turns toward the cursor smoothly, with no overshoot
const kl = 1 - Math.exp(-dt * 2.5);
lookX += (lookTX - lookX) * kl;
lookY += (lookTY - lookY) * kl;
// now and then a shooting star crosses the sky on its own
if (p.meteors > 0 && flow > nextMeteor) {
meteor();
nextMeteor = flow + (60 / p.meteors) * (0.5 + Math.random());
}
for (let i = mets.length - 1; i >= 0; i--) if (flow - mets[i].t > 1.3) mets.splice(i, 1);
for (let i = waves.length - 1; i >= 0; i--) if (flow - waves[i].t > 3.1) waves.splice(i, 1);
slow = slow * 0.97 + (rawDt > 1 / 45 ? 0.03 : 0);
if (slow > 0.5 && rs === 1) {
rs = 0.8;
resize();
}
draw();
};
const io = new IntersectionObserver(([en]) => {
visible = en.isIntersecting;
prev = performance.now();
});
const start = () => {
canvas.style.opacity = "1";
if (still) {
draw();
redraw.current = draw;
return;
}
intro = gsap.to(s, { intro: 1, duration: 2.6, ease: "power2.out", delay: 0.05 });
prev = performance.now();
io.observe(host);
gsap.ticker.add(tick);
};
const im = new Image();
im.crossOrigin = "anonymous";
im.decoding = "async";
im.onload = () => {
if (disposed) return;
gl.bindTexture(gl.TEXTURE_2D, imgTex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, im);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.generateMipmap(gl.TEXTURE_2D);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
imgW = im.naturalWidth;
imgH = im.naturalHeight;
ready = true;
start();
};
im.src = image;
return () => {
disposed = true;
redraw.current = null;
gsap.ticker.remove(tick);
intro?.kill();
st?.kill();
io.disconnect();
ro.disconnect();
host.removeEventListener("pointermove", move);
host.removeEventListener("pointerleave", leave);
host.removeEventListener("pointerdown", down);
host.removeEventListener("wheel", wheel);
gsap.killTweensOf(s);
freeTargets();
gl.deleteTexture(imgTex);
gl.deleteProgram(sceneProg);
gl.deleteProgram(blurProg);
gl.deleteProgram(brightProg);
gl.deleteProgram(compProg);
gl.deleteBuffer(vbo);
gl.deleteVertexArray(vao);
canvas.remove();
gl.getExtension("WEBGL_lose_context")?.loseContext();
};
}, [image, scroller]);
return (
<div ref={hostRef} className={["isolate overflow-hidden", className].filter(Boolean).join(" ")} style={{ background }}>
{children && <div className="relative z-10 h-full">{children}</div>}
</div>
);
}
export default GalaxyDrift;
One prompt, any AI agent
Paste into Claude Code, Codex, Cursor or Windsurf. It carries your tweaks and the full source, so the agent installs it exactly.
Props
14 propsimagestringThe galaxy photo, at infinity behind the stars (a star-free photo works best).default "/backgrounds/galaxy-drift/galaxy.jpg"default "/backgrounds/galaxy-drift/galaxy.jpg"starsnumberHow many stars, 0 to 2.default 1default 1twinklenumberHow much the distant stars twinkle.default 1default 1cruisenumberSpeed of the slow idle cruise through the stars.default 1default 1thrustnumberHow hard scrolling thrusts you forward.default 1default 1meteorsnumberShooting stars per minute on their own (0 for none).default 6default 6telescopenumberStrength of the telescope under the cursor.default 1default 1exposurenumberBrightness of the galaxy band.default 1default 1glownumberStrength of the bloom on the stars.default 0.6default 0.6backgroundstringShown while the photo loads.default "#030304"default "#030304"interactivebooleanSteering, telescope, click warp, scroll flight.default truedefault truescrollerElement | nullScroll container, if the page does not scroll the window.childrenReactNodeForeground content, drawn above the sky.classNamestringSize it, e.g. h-screen w-full.