All articles
Three.jsGLSLWebGLSpace

Rendering a Black Hole in a Single Three.js Shader

How the black hole on my site is drawn on one quad: a Keplerian accretion disk, Doppler beaming, faked lensing, bent starlight and theme-aware alpha.

Tushar Pachouri20 min read

The black hole that drifts beside the Services section of this site has no model, texture or video behind it: just two triangles and a fragment shader that computes every pixel's colour on every frame. This post walks through that shader in the order it builds the picture, using the site's real code.

TL;DR

  • Everything is drawn on one camera-facing quad: the shader stacks closed-form layers for the shadow, disk, lensed arcs, photon ring and stars.
  • The disk is a squashed circle streaked with noise that shears at Keplerian speed, coloured by a blackbody ramp and brighter on the approaching side.
  • The disk's lensing is faked with hand-placed rings, but the stars go through a real point-mass lens equation, so they smear into arcs.
  • A filmic tone map outputs colour and alpha together, so the result composites over a white page and a black one.
  • It is physically motivated, not simulated.

One quad, one material

createBlackHole() builds a THREE.PlaneGeometry(2, 2) and a THREE.ShaderMaterial with transparent: true and depthWrite: false. The camera faces the quad, so it acts as a billboard; the vertex shader only passes UVs along:

GLSL
varying vec2 vUv;
void main() {
  vUv = uv;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

Two uniforms drive the rendering: uTime, advanced every frame, and uDark, 1 in dark theme and 0 in light. The function returns the small interface every object in the site's space scene implements:

TypeScript
import * as THREE from "three";

export type FrameContext = {
  dark: boolean;
  camera: THREE.PerspectiveCamera;
};

export type SpaceObject = {
  object: THREE.Object3D;
  /** Widest on-screen size of the object at scale 1, in world units. */
  extent: number;
  update?: (t: number, ctx: FrameContext) => void;
  setTheme?: (dark: boolean) => void;
  dispose?: () => void;
};

The live file also multiplies four of the shader's lines by click-interaction uniforms and advances uTime faster on hover and clicks; I've stripped both to keep the focus on rendering. The complete rendering-only file is at the end.

Centred coordinates and a slight tilt

First, UVs are mapped from 0..1 to centred coordinates in -1..1:

GLSL
vec2 p = vUv * 2.0 - 1.0;
float cr = cos(-0.12), sr = sin(-0.12);
p = mat2(cr, -sr, sr, cr) * p;
float r = length(p);
float rh = 0.19;                                  // shadow radius

The rotation adds a tilt of about 7 degrees, because a perfectly level disk looks staged. Two details catch people out: GLSL's mat2 constructor fills columns, not rows, and rotating the coordinates turns the image the other way. Here the drawing ends up rotated clockwise, left end of the disk higher. If yours tilts the wrong way, flip the angle's sign.

The shadow

GLSL
float shadow = 1.0 - smoothstep(rh - 0.006, rh + 0.004, r);

A filled disc with an edge just soft enough to antialias, used later as a mask.

The dark region is not the event horizon (the code comments loosely call its edge that). For a non-spinning black hole, any light ray aimed within about 2.6 horizon radii of the centre is captured, so the shadow looks about 2.6 times the horizon's size.

The accretion disk

A circle seen almost edge-on

A flat ring of gas seen from just above its plane projects to a thin ellipse. The shader stretches the vertical axis back out so it can work in the disk's own plane:

GLSL
float squash = 0.14;
vec2 q = vec2(p.x, p.y / squash);
float dr = length(q);
float ang = atan(q.y, q.x);

dr is the radius in the disk plane and ang the angle around it. A squash of 0.14 is the cosine of the viewing angle, so we sit about 8 degrees above edge-on. Points with p.y < 0 belong to the near half of the disk.

Keplerian shear with fbm

By Kepler's third law, orbital period squared is proportional to radius cubed, so angular speed falls as r^-1.5 and inner gas laps outer gas. The shader uses that to smear noise into streaks:

GLSL
float omega = 0.55 / pow(max(dr, 0.22), 1.5);    // Keplerian
float sh = ang + uTime * omega;
float streak = fbm(vec2(dr * 10.0, sh * 2.5)) * 0.65 + fbm(vec2(dr * 30.0, sh * 6.0)) * 0.35;

The noise is sampled in (radius, angle) space, so features already lie along orbits. Adding uTime * omega turns each radius at its own speed, and any blob gets stretched into an arc as its inner edge runs ahead. max(dr, 0.22) stops the speed blowing up at the centre, where band is zero anyway because the disk starts at 0.235. A coarse layer gives broad bands and a fine one gives filaments.

The noise is value noise summed into five octaves of fractal Brownian motion (fbm), shared with the site's other shader objects:

TypeScript
// Value noise + fBm, shared by the shader objects
export const NOISE_GLSL = /* glsl */ `
  float hash21(vec2 p) {
    p = fract(p * vec2(123.34, 456.21));
    p += dot(p, p + 45.32);
    return fract(p.x * p.y);
  }
  float vnoise(vec2 p) {
    vec2 i = floor(p);
    vec2 f = fract(p);
    float a = hash21(i);
    float b = hash21(i + vec2(1.0, 0.0));
    float c = hash21(i + vec2(0.0, 1.0));
    float d = hash21(i + vec2(1.0, 1.0));
    vec2 u = f * f * (3.0 - 2.0 * f);
    return mix(a, b, u.x) + (c - a) * u.y * (1.0 - u.x) + (d - b) * u.x * u.y;
  }
  float fbm(vec2 p) {
    float v = 0.0;
    float a = 0.5;
    for (int i = 0; i < 5; i++) {
      v += a * vnoise(p);
      p = p * 2.03 + vec2(17.1, 9.2);
      a *= 0.5;
    }
    return v;
  }
`;

vnoise blends random corner values with a smooth curve; in fbm, the odd 2.03 and the offset stop the octaves lining up into a grid.

What the constants mean in practice (each TypeScript check in this post is standalone; run it with npx tsx file.ts):

TypeScript
// The disk's tilt and orbital speeds, using the shader's constants
const squash = 0.14;
const tilt = (Math.acos(squash) * 180) / Math.PI;
console.log(`disk tilted ${tilt.toFixed(1)} degrees away from face-on`);

const omega = (r: number) => 0.55 / Math.pow(Math.max(r, 0.22), 1.5);
for (const r of [0.25, 0.5, 0.97]) {
  const orbit = (2 * Math.PI) / omega(r);
  console.log(`r = ${r.toFixed(2)}: ${omega(r).toFixed(2)} rad/s, one orbit every ${orbit.toFixed(1)} s`);
}
Text
disk tilted 82.0 degrees away from face-on
r = 0.25: 4.40 rad/s, one orbit every 1.4 s
r = 0.50: 1.56 rad/s, one orbit every 4.0 s
r = 0.97: 0.58 rad/s, one orbit every 10.9 s
DISK ANGULAR SPEED, ω = 0.55 / r^1.5 rad/s 0 1 2 3 4 5 0.2 0.4 0.6 0.8 1 r, radius in the disk plane r = 0.25 4.40 rad/s, orbit 1.4 s r = 0.50 1.56 rad/s, orbit 4.0 s r = 0.97 0.58 rad/s, orbit 10.9 s
Inner gas orbits several times faster than outer gas, which is what shears the noise into streaks.

A blackbody colour ramp

Heated gas glows deep red, then orange, yellow and white. A real blackbody continues to blue-white; this ramp stops at warm white so the light stays warm in both themes:

GLSL
// Approximate blackbody colour ramp: 0 = cool deep red, 1 = white-hot
vec3 blackbody(float t) {
  vec3 c = mix(vec3(0.45, 0.08, 0.02), vec3(1.0, 0.42, 0.08), smoothstep(0.0, 0.35, t));
  c = mix(c, vec3(1.0, 0.78, 0.32), smoothstep(0.3, 0.7, t));
  return mix(c, vec3(1.0, 0.96, 0.86), smoothstep(0.72, 1.0, t));
}

The disk maps radius to temperature and brightness:

GLSL
float inner = 0.235, outer = 0.97;
float band = smoothstep(inner, inner + 0.035, dr) * (1.0 - smoothstep(0.5, outer, dr));
float u = clamp((dr - inner) / (outer - inner), 0.0, 1.0);
float beam = 1.0 - 0.62 * cos(ang);               // approaching side (left) brighter
float temp = clamp((1.0 - u) * 0.9 + 0.18 * (beam - 1.0), 0.0, 1.0);
float diskI = band * (0.2 + 1.25 * streak) * beam * (1.5 - u);

band fades the disk in at the inner edge and out towards the rim; u runs from 0 at the inner edge to 1 at the outer, so temperature and brightness fall outwards. A real thin disk cools roughly as r^-3/4 away from its inner edge; a linear ramp is close enough here.

Doppler beaming

Gas this close orbits at a sizeable fraction of light speed, and relativity makes the side moving towards you much brighter and bluer; the real boost goes as roughly the third or fourth power of the Doppler factor. The shader uses a cosine instead: beam is 1.62 on the left and 0.38 on the right, and it nudges temp up so the bright side also looks hotter, a stand-in for blueshift. My understanding is that the film's Gargantua left this asymmetry out to keep the image readable.

An orbiting hot spot

GLSL
// Hot spot riding the innermost stable orbit, smeared along its path
float spotAng = mod(ang + uTime * 0.55 / pow(0.3, 1.5) * 0.35 + 3.14159, 6.28318) - 3.14159;
diskI += exp(-pow((dr - 0.3) / 0.035, 2.0) - spotAng * spotAng * 6.0) * beam * 1.6;
float nearSide = smoothstep(0.012, -0.012, p.y);

A Gaussian blob in radius and angle, just outside the disk's inner edge, going round about every 5.4 seconds. The 0.35 deliberately slows it to about a third of the local gas speed, so the flare is easy to follow. The mod wraps the angle difference into -π..π so the spot doesn't jump where atan wraps, and beam makes it flare on the bright side. The idea comes from infrared flares near Sagittarius A*, our galaxy's central black hole, interpreted as orbiting hot spots.

Faking the lensing

The far side arching over the top

The bright arc over the shadow is the far side of the disk: light from its top surface is bent over the hole towards you.

GLSL
float ra = atan(p.y, p.x);
float up = smoothstep(-0.15, 0.55, p.y / max(r, 0.001));
float lens = exp(-pow((r - rh * 1.33) / (rh * 0.22), 2.0));
float lensTex = 0.45 + 0.75 * fbm(vec2(ra * 4.0 - uTime * 0.35, r * 18.0));
float lensTop = lens * lensTex * (0.2 + 1.0 * up) * (1.0 - 0.5 * cos(ra));

lens is a Gaussian ring at 1.33 shadow radii with drifting texture from lensTex. up uses p.y / r, the sine of the screen angle, to keep the ring strong over the top and fade it down the sides. The cos(ra) term repeats the left-bright Doppler asymmetry.

The secondary image and the photon ring

GLSL
float lensBottom = exp(-pow((r - rh * 1.11) / (rh * 0.06), 2.0)) * smoothstep(0.1, -0.5, p.y / max(r, 0.001)) * 0.7;

float photon = exp(-pow((r - rh * 1.035) / 0.0065, 2.0));
float glow = exp(-pow(r / 0.42, 2.0));

Light from the far disk's underside can instead bend under the hole, giving a thin arc below the shadow: the secondary image. Closer still is the photon ring: light that skimmed around the hole, sometimes more than once, before escaping. A real render shows a stack of ever-thinner rings there; one sharp Gaussian stands in for all of them. glow is a faint, wide halo.

Draw order instead of depth

Within one quad, depth comes from the order layers are added:

GLSL
vec3 col = vec3(0.0);
col += blackbody(0.85) * (lensTop + lensBottom) * 1.15;
col += blackbody(temp) * diskI * (1.0 - nearSide);
col += blackbody(0.45) * glow * mix(0.12, 0.22, uDark);
col += vec3(0.85, 0.9, 1.0) * stars * uDark;
col *= 1.0 - shadow;                              // everything behind is swallowed
col += vec3(1.0, 0.93, 0.78) * photon * 1.4;
col += blackbody(temp) * diskI * nearSide;         // near side crosses in front

Arcs, the far half of the disk, glow and stars go in first; the shadow multiplies them away; then the photon ring and the near half of the disk land on top. nearSide is a soft step across p.y = 0, so the near half crosses the shadow as a glowing band.

The shader adds layers bottom to top, and the shadow multiply hides only the layers added before it.

Bending the background stars

The stars use real lensing maths, starting from a cheap field with at most one star per grid cell:

GLSL
// Sparse star field: one candidate star per grid cell
float starField(vec2 s) {
  vec2 g = s * 15.0;
  vec2 id = floor(g);
  float h = hash21(id);
  if (h < 0.86) return 0.0;
  vec2 pos = vec2(hash21(id + 7.1), hash21(id + 3.7)) * 0.7 + 0.15;
  float d = length(fract(g) - pos);
  return smoothstep(0.09, 0.0, d) * (0.4 + 0.6 * (h - 0.86) / 0.14);
}

Instead of drawing stars where they are, each pixel asks which part of the sky lands on it. For a point mass, light arriving at angle θ from the lens left a source at β = θ − θE²/θ, where θE is the Einstein radius:

GLSL
// Gravitationally lensed background stars
float thetaE = rh * 1.55;
vec2 src = p * (1.0 - thetaE * thetaE / max(r * r, 0.0001));
float stars = starField(src + vec2(3.1, 1.7)) * (1.0 - shadow) * smoothstep(rh * 1.05, rh * 1.5, r);
float magnify = clamp(1.0 / max(abs(1.0 - pow(thetaE / max(r, 0.001), 4.0)), 0.001), 1.0, 4.0);
stars *= min(1.6, 0.6 + 0.4 * magnify) * (1.0 - smoothstep(0.75, 0.98, r));

src is that equation in vector form. Inside the Einstein ring the factor goes negative, so the pixel looks at the opposite side of the sky: a second, mirrored star field just outside the shadow. magnify is the point-lens magnification, 1 / |1 − (θE/θ)⁴|, clamped. Images are stretched along the ring and squeezed across it, which turns dots into arcs:

TypeScript
// Point-mass lens: where each pixel looks in the sky, and how a star's image is distorted
const rh = 0.19;          // shadow radius in the shader
const thetaE = rh * 1.55; // Einstein radius

for (const theta of [0.25, 0.3, 0.35, 0.45, 0.6, 0.9]) {
  const beta = theta - (thetaE * thetaE) / theta; // source position
  const along = Math.abs(theta / beta);           // stretch along the ring
  const across = 1 / (1 + (thetaE / theta) ** 2); // squeeze across it
  const flip = beta < 0 ? "  (mirrored)" : "";
  console.log(
    `theta ${theta.toFixed(2)}  beta ${beta.toFixed(3).padStart(6)}  ` +
      `along x${along.toFixed(2).padEnd(5)}  across x${across.toFixed(2)}${flip}`,
  );
}
Text
theta 0.25  beta -0.097  along x2.58   across x0.42  (mirrored)
theta 0.30  beta  0.011  along x27.53  across x0.51
theta 0.35  beta  0.102  along x3.42   across x0.59
theta 0.45  beta  0.257  along x1.75   across x0.70
theta 0.60  beta  0.455  along x1.32   across x0.81
theta 0.90  beta  0.804  along x1.12   across x0.90

Next to θE (about 0.29) a star stretches more than twenty times along the ring. This weak-field equation is good far from a black hole and increasingly wrong close in, where real light bends far harder. The shader fades stars out near the shadow anyway.

WHERE EACH LAYER SITS ALONG THE RADIUS rh shadow r < rh = 0.19 photon ring 1.035 rh arc under the shadow 1.11 rh arc over the top 1.33 rh accretion disk 0.235 to 0.97, spot 0.3 lensed stars Einstein ring 1.55 rh 0 0.2 0.4 0.6 0.8 1 r, distance from the centre of the quad (edge = 1), along the disk's midline
Every layer of the shader is a simple function of r, and most of them crowd just outside the shadow.

Tone mapping and alpha for both themes

GLSL
float edge = 1.0 - smoothstep(0.78, 1.0, r);
col *= edge;

// Filmic tone map: light, not paint
vec3 mapped = 1.0 - exp(-col * 1.7);
float lum = max(max(mapped.r, mapped.g), mapped.b);
float a = clamp(max(shadow * edge, lum * 1.1), 0.0, 1.0);
vec3 outc = min(mapped / max(a, 0.0001), vec3(1.0));
// Light theme: white stars would vanish on the page, so draw them as ink
float inkStar = stars * (1.0 - uDark) * 0.8;
outc = mix(outc, vec3(0.08), inkStar * (1.0 - lum));
a = max(a, inkStar);
gl_FragColor = vec4(outc, a);

edge fades everything out before the square's border. 1.0 - exp(-col * 1.7) is a simple filmic curve: dim values pass almost linearly, bright ones approach 1 without clipping, and very hot regions drift to white as each channel saturates.

The alpha line makes one shader work on two backgrounds. Alpha is the pixel's brightness (1 inside the shadow), and colour is divided by it because three.js's default NormalBlending multiplies colour by alpha. The canvas is cleared to transparent, so the buffer ends up holding mapped premultiplied, and the browser composites it over the page. On black you get the tone-mapped light unchanged; on white, light becomes a tint whose strength follows its brightness, and the shadow stays solid black in both:

TypeScript
// The shader's tone map and alpha, then the same pixel composited over a black and a white page
type RGB = [number, number, number];

function shaderOutput(col: RGB): { rgb: RGB; a: number } {
  const mapped = col.map((c) => 1 - Math.exp(-c * 1.7)) as RGB;
  const lum = Math.max(...mapped);
  const a = Math.min(Math.max(lum * 1.1, 0), 1);
  const rgb = mapped.map((m) => Math.min(m / Math.max(a, 0.0001), 1)) as RGB;
  return { rgb, a };
}

const over = ({ rgb, a }: { rgb: RGB; a: number }, page: number) =>
  rgb.map((c) => Math.round((c * a + page * (1 - a)) * 255));

const orange: RGB = [1.0, 0.42, 0.08];
for (const k of [0.1, 0.5, 2.0]) {
  const out = shaderOutput(orange.map((c) => c * k) as RGB);
  console.log(
    `intensity ${k.toFixed(1)}: alpha ${out.a.toFixed(2)}  ` +
      `on black rgb(${over(out, 0).join(", ")})  on white rgb(${over(out, 1).join(", ")})`,
  );
}
Text
intensity 0.1: alpha 0.17  on black rgb(40, 18, 3)  on white rgb(251, 229, 215)
intensity 0.5: alpha 0.63  on black rgb(146, 77, 17)  on white rgb(240, 171, 111)
intensity 2.0: alpha 1.00  on black rgb(246, 194, 61)  on white rgb(246, 194, 61)

Note: From my reading of the three.js source, a ShaderMaterial skips tone mapping and output colour-space conversion unless main() ends with #include <tonemapping_fragment> and #include <colorspace_fragment>, as the built-in materials do, so what the shader writes is what gets blended. Worth checking for your version.

What uDark changes

Stars are added only in dark theme, since white dots vanish on white; in light theme they return as ink, with inkStar pulling the colour towards near-black and raising alpha. The glow is weaker there too. A theme switch just sets the uniform, so nothing recompiles.

Placement and performance

The black hole lives on a fixed, full-viewport canvas behind the content, anchored to the right of #services and 360 CSS pixels wide on desktop, smaller on narrow screens. Because the quad is exactly 2 units wide, sizing it is one conversion from pixels to world units at its depth:

TypeScript
// World units per CSS pixel at a given distance in front of a perspective camera
function worldPerPixel(fovDeg: number, depth: number, viewportHeight: number) {
  return (2 * depth * Math.tan((fovDeg * Math.PI) / 360)) / viewportHeight;
}

const k = worldPerPixel(55, 60, 900); // camera fov, black hole depth, a 900 px tall viewport
const extent = 2;                      // the quad is 2 world units wide at scale 1
const scale = (360 * k) / extent;      // make it 360 CSS px wide
console.log(`1 px = ${k.toFixed(4)} world units at depth 60, quad scale = ${scale.toFixed(2)}`);
Text
1 px = 0.0694 world units at depth 60, quad scale = 12.49

Each pixel runs three fbm calls at five octaves, so fifteen value-noise lookups, plus a few star hashes. With the site's 1.5 device-pixel-ratio cap that is up to about 290,000 fragments while the object is on screen, and none once it scrolls away, because the scene sets visible = false.

One cheap win: the corners outside r = 1, about a fifth of the quad, always come out fully transparent. An early exit right after r is computed skips them with identical output:

GLSL
if (r > 1.0) { gl_FragColor = vec4(0.0); return; }

Three things to watch

Shear never stops winding

Because sh = ang + uTime * omega, the angle difference between two radii grows forever, and neighbouring pixels sample the noise further and further apart:

TypeScript
// How far apart neighbouring pixels sample the disk noise as time goes on
const pxPerUnit = 360 / 2;  // the 2-unit quad is drawn 360 CSS px wide on desktop
const r = 0.5;              // halfway out along the disk
const shear = 1.5 * 0.55 * Math.pow(r, -2.5); // |d(omega)/dr|

for (const t of [1, 5, 15, 60]) {
  const coarse = (2.5 * t * shear) / pxPerUnit; // fbm(vec2(dr * 10.0, sh * 2.5))
  const fine = (6.0 * t * shear) / pxPerUnit;   // fbm(vec2(dr * 30.0, sh * 6.0))
  console.log(`t = ${String(t).padStart(2)} s: ${coarse.toFixed(2)} / ${fine.toFixed(2)} noise cells per pixel`);
}
Text
t =  1 s: 0.06 / 0.16 noise cells per pixel
t =  5 s: 0.32 / 0.78 noise cells per pixel
t = 15 s: 0.97 / 2.33 noise cells per pixel
t = 60 s: 3.89 / 9.33 noise cells per pixel

Once a pixel spans about a whole noise cell, neighbours stop being correlated and streaks dissolve into grain: the fine layer gets there in about six seconds, the coarse one in about fifteen, sooner at smaller radii. Astronomers call this the winding problem when it affects spiral arms.

The fix borrows from flow-map water shaders: two copies of the texture, half a period apart, each restarting with fresh noise and cross-faded with the other.

GLSL
const float PERIOD = 6.0;

// One copy of the sheared disk texture. It restarts every PERIOD seconds
// with fresh noise, so the shear never builds up past one period.
float shearedStreak(float dr, float ang, float omega, float phase) {
  float cycle = uTime / PERIOD + phase;
  float t = fract(cycle) * PERIOD;
  vec2 seed = vec2(mod(floor(cycle), 32.0) * 13.7, phase * 29.3);
  float sh = ang - t * omega;
  return fbm(vec2(dr * 10.0, sh * 2.5) + seed) * 0.65
       + fbm(vec2(dr * 30.0, sh * 6.0) + seed) * 0.35;
}

Put it after the noise helpers, follow it with this blend, and replace the sh and streak lines in main() with float streak = diskStreak(dr, ang, omega);:

GLSL
// Cross-fades the two copies; the return line keeps contrast steady through the blend
float diskStreak(float dr, float ang, float omega) {
  float w = abs(fract(uTime / PERIOD) * 2.0 - 1.0);
  float s = mix(shearedStreak(dr, ang, omega, 0.0), shearedStreak(dr, ang, omega, 0.5), w);
  return 0.48 + (s - 0.48) / sqrt(w * w + (1.0 - w) * (1.0 - w));
}

w is 1 when the first copy restarts and 0 when the second does, so restarts never show. A plain mix lowers contrast by up to about a third, pulsing every three seconds; the return line undoes that by rescaling the deviation from the streak's mean, about 0.48. The shear stays bounded, at double the disk's noise cost, but at r = 0.3 the fine layer still grains for much of each six-second cycle; a PERIOD of 2-3 seconds is cleaner but pulses faster.

Each copy restarts with fresh noise only at the moment its weight in the blend is zero.

Make the spin agree with the beaming

With ang + uTime * omega, noise features drift towards smaller angles: clockwise on screen. Seen from slightly above, a clockwise disk carries its right side towards you, yet beam brightens the left, and the lensed arc (ra * 4.0 - uTime * 0.35) already drifts the other way. Flipping two signs makes all three agree (the shear snippets above already do):

Diff
-        float sh = ang + uTime * omega;
+        float sh = ang - uTime * omega;
-        float spotAng = mod(ang + uTime * 0.55 / pow(0.3, 1.5) * 0.35 + 3.14159, 6.28318) - 3.14159;
+        float spotAng = mod(ang - uTime * 0.55 / pow(0.3, 1.5) * 0.35 + 3.14159, 6.28318) - 3.14159;

The seam where atan wraps

ang and ra jump from π to −π along the left half of the midline. The hot spot's mod() copes, but fbm isn't periodic, so the streaks and lensTex can show a seam across the disk's brightest side; check a still frame. Near ±π, blend in a sample taken one turn away so both sides of the line match:

GLSL
// Replaces the streak and lensTex lines in main(), using diskStreak from above
float streak = diskStreak(dr, ang, omega);
float seam = 0.5 * smoothstep(2.6, 3.14159, abs(ang));
if (seam > 0.0) streak = mix(streak, diskStreak(dr, ang - 6.28318 * sign(ang), omega), seam);

float lensN = fbm(vec2(ra * 4.0 - uTime * 0.35, r * 18.0));
float raSeam = 0.5 * smoothstep(2.6, 3.14159, abs(ra));
if (raSeam > 0.0) lensN = mix(lensN, fbm(vec2((ra - 6.28318 * sign(ra)) * 4.0 - uTime * 0.35, r * 18.0)), raSeam);
float lensTex = 0.45 + 0.75 * lensN;

The if keeps the doubled noise cost to the sixth of the disk nearest the seam.

What this is not

Physically accurate black hole renders, like the simulations astronomers compare against Event Horizon Telescope data, come from general-relativistic ray tracing: each pixel's light ray is traced backwards through curved spacetime until it hits the disk, the sky or the horizon, and the lensing, shadow shape and colour shifts fall out of the physics. Interstellar's Gargantua came from such a renderer, built for a spinning black hole; the team, including physicist Kip Thorne, later published the method.

This shader places rings and arcs where those renders show them, picks widths by eye, uses a weak-field lens for the stars, and skips gravitational redshift and the lopsided shadow of a spinning hole. In exchange it is about a hundred lines of GLSL on one quad: cheap enough for a portfolio's margin, close enough to read as a black hole at a glance.

The complete file

The rendering-only blackHole.ts, importing NOISE_GLSL and SpaceObject from the shared module shown earlier:

TypeScript
import * as THREE from "three";
import { NOISE_GLSL, type SpaceObject } from "./shared";

// Black hole in the style of Interstellar's Gargantua, drawn in one shader on a camera-facing
// quad. Physically motivated, not simulated:
// - accretion disk seen nearly edge-on, hottest (white-yellow) near the inner edge, cooling to
//   orange and deep red outwards; gas shears with Keplerian speed (inner orbits faster)
// - relativistic Doppler beaming: the side moving towards us is brighter and hotter
// - gravitational lensing: the far side of the disk appears as a bright arc over the top of
//   the shadow, plus a thin secondary image underneath
// - a razor-thin photon ring just outside the event horizon, and a warm glow
// - background stars bent by the lens: each pixel looks up the star field at the "source"
//   position of a point-mass lens (β = θ − θE²/θ), so stars smear into arcs near the ring
//   and a second, mirrored image of the sky appears just outside it
// - a bright hot spot of gas orbiting at the inner edge, as seen in real flares from Sgr A*
// The shadow is always black and the light is always warm, in both themes.
export function createBlackHole(): SpaceObject {
  const material = new THREE.ShaderMaterial({
    transparent: true,
    depthWrite: false,
    uniforms: { uTime: { value: 0 }, uDark: { value: 1 } },
    vertexShader: /* glsl */ `
      varying vec2 vUv;
      void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
      }
    `,
    fragmentShader: /* glsl */ `
      uniform float uTime;
      uniform float uDark;
      varying vec2 vUv;
      ${NOISE_GLSL}

      // Approximate blackbody colour ramp: 0 = cool deep red, 1 = white-hot
      vec3 blackbody(float t) {
        vec3 c = mix(vec3(0.45, 0.08, 0.02), vec3(1.0, 0.42, 0.08), smoothstep(0.0, 0.35, t));
        c = mix(c, vec3(1.0, 0.78, 0.32), smoothstep(0.3, 0.7, t));
        return mix(c, vec3(1.0, 0.96, 0.86), smoothstep(0.72, 1.0, t));
      }

      // Sparse star field: one candidate star per grid cell
      float starField(vec2 s) {
        vec2 g = s * 15.0;
        vec2 id = floor(g);
        float h = hash21(id);
        if (h < 0.86) return 0.0;
        vec2 pos = vec2(hash21(id + 7.1), hash21(id + 3.7)) * 0.7 + 0.15;
        float d = length(fract(g) - pos);
        return smoothstep(0.09, 0.0, d) * (0.4 + 0.6 * (h - 0.86) / 0.14);
      }

      void main() {
        vec2 p = vUv * 2.0 - 1.0;
        float cr = cos(-0.12), sr = sin(-0.12);
        p = mat2(cr, -sr, sr, cr) * p;
        float r = length(p);
        float rh = 0.19;                                  // shadow radius

        // ── Accretion disk ────────────────────────────────────────────────
        float squash = 0.14;
        vec2 q = vec2(p.x, p.y / squash);
        float dr = length(q);
        float ang = atan(q.y, q.x);
        float omega = 0.55 / pow(max(dr, 0.22), 1.5);    // Keplerian
        float sh = ang + uTime * omega;
        float streak = fbm(vec2(dr * 10.0, sh * 2.5)) * 0.65 + fbm(vec2(dr * 30.0, sh * 6.0)) * 0.35;
        float inner = 0.235, outer = 0.97;
        float band = smoothstep(inner, inner + 0.035, dr) * (1.0 - smoothstep(0.5, outer, dr));
        float u = clamp((dr - inner) / (outer - inner), 0.0, 1.0);
        float beam = 1.0 - 0.62 * cos(ang);               // approaching side (left) brighter
        float temp = clamp((1.0 - u) * 0.9 + 0.18 * (beam - 1.0), 0.0, 1.0);
        float diskI = band * (0.2 + 1.25 * streak) * beam * (1.5 - u);
        // Hot spot riding the innermost stable orbit, smeared along its path
        float spotAng = mod(ang + uTime * 0.55 / pow(0.3, 1.5) * 0.35 + 3.14159, 6.28318) - 3.14159;
        diskI += exp(-pow((dr - 0.3) / 0.035, 2.0) - spotAng * spotAng * 6.0) * beam * 1.6;
        float nearSide = smoothstep(0.012, -0.012, p.y);

        // ── Lensed images of the far side ─────────────────────────────────
        float ra = atan(p.y, p.x);
        float up = smoothstep(-0.15, 0.55, p.y / max(r, 0.001));
        float lens = exp(-pow((r - rh * 1.33) / (rh * 0.22), 2.0));
        float lensTex = 0.45 + 0.75 * fbm(vec2(ra * 4.0 - uTime * 0.35, r * 18.0));
        float lensTop = lens * lensTex * (0.2 + 1.0 * up) * (1.0 - 0.5 * cos(ra));
        float lensBottom = exp(-pow((r - rh * 1.11) / (rh * 0.06), 2.0)) * smoothstep(0.1, -0.5, p.y / max(r, 0.001)) * 0.7;

        float photon = exp(-pow((r - rh * 1.035) / 0.0065, 2.0));
        float glow = exp(-pow(r / 0.42, 2.0));
        float shadow = 1.0 - smoothstep(rh - 0.006, rh + 0.004, r);

        // Gravitationally lensed background stars
        float thetaE = rh * 1.55;
        vec2 src = p * (1.0 - thetaE * thetaE / max(r * r, 0.0001));
        float stars = starField(src + vec2(3.1, 1.7)) * (1.0 - shadow) * smoothstep(rh * 1.05, rh * 1.5, r);
        float magnify = clamp(1.0 / max(abs(1.0 - pow(thetaE / max(r, 0.001), 4.0)), 0.001), 1.0, 4.0);
        stars *= min(1.6, 0.6 + 0.4 * magnify) * (1.0 - smoothstep(0.75, 0.98, r));

        vec3 col = vec3(0.0);
        col += blackbody(0.85) * (lensTop + lensBottom) * 1.15;
        col += blackbody(temp) * diskI * (1.0 - nearSide);
        col += blackbody(0.45) * glow * mix(0.12, 0.22, uDark);
        col += vec3(0.85, 0.9, 1.0) * stars * uDark;
        col *= 1.0 - shadow;                              // everything behind is swallowed
        col += vec3(1.0, 0.93, 0.78) * photon * 1.4;
        col += blackbody(temp) * diskI * nearSide;         // near side crosses in front

        float edge = 1.0 - smoothstep(0.78, 1.0, r);
        col *= edge;

        // Filmic tone map: light, not paint
        vec3 mapped = 1.0 - exp(-col * 1.7);
        float lum = max(max(mapped.r, mapped.g), mapped.b);
        float a = clamp(max(shadow * edge, lum * 1.1), 0.0, 1.0);
        vec3 outc = min(mapped / max(a, 0.0001), vec3(1.0));
        // Light theme: white stars would vanish on the page, so draw them as ink
        float inkStar = stars * (1.0 - uDark) * 0.8;
        outc = mix(outc, vec3(0.08), inkStar * (1.0 - lum));
        a = max(a, inkStar);
        gl_FragColor = vec4(outc, a);
      }
    `,
  });
  const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material);
  return {
    object: quad,
    extent: 2,
    update: (t) => {
      material.uniforms.uTime.value = t;
    },
    setTheme: (dark) => {
      material.uniforms.uDark.value = dark ? 1 : 0;
    },
  };
}

Stuck on something like this?

I build and fix full-stack products for startups and indie founders. Tell me what's broken.

Get in touch