SCENE.LOG
scene ▸ node[07]
2026-10-25 · 8 min

A 3D photo card carousel with Three.js

interaction shaders three.js

A short detour from the stylized nature series. Aristide Benoist, a creative developer I’ve been following for a while, shared a video on X of a framework he built: a Rust back end and a front end rendered entirely with native WebGPU. The video shows a 3D carousel that I wanted to recreate in Three.js.

// the original post: the carousel in the video is the one I'm recreating here

The result fits in under 300 lines of JavaScript across three files, and depends on nothing but three:

src/main.js        renderer, camera, textures, drag, frame loop
src/fan.js         the ring: construction, opening, rotation, tilt, bend
src/material.js    the card shader

Here’s the final result, quite close to the one in the video: the cards spin around a fixed point, you can tilt the carousel, spin it by hand, and the cards bend under the effect of speed:

// drag to spin · vertical drag to tilt

And here’s the final version, with a few improvements, integrated into a photographer’s portfolio:

// the carousel in context: from the gallery to the carousel, hand rotation and card bending

Setup

The usual Three.js setup: a full-screen canvas, a WebGLRenderer, a PerspectiveCamera slightly above the ring plane and looking at the origin. No camera controls, since it’s the object that moves, not the viewpoint. The loop goes through setAnimationLoop, with the delta between two frames clamped to 0.1 s so that a tab put in the background doesn’t make the animation jump on return.

// main.js
renderer.setAnimationLoop((now) => {
  const delta = Math.min((now - last) / 1000, 0.1);
  last = now;
  fan.tick(delta);
  renderer.render(scene, camera);
});

Everything tunable lives in a config object at the top of the file: sizes, camera, speeds, springs. The values quoted below come from there, and they’re also the ones behind the sliders of the demo above.

Building a card: texture, shader and mesh

A card is a texture, a material and a mesh. In that order.

Textures

Nothing is built before every image has arrived, because the real dimensions of the photos drive the cropping, and I prefer one complete opening to cards popping in one by one.

// main.js
async function loadTextures(urls) {
  const loader = new THREE.TextureLoader();
  loader.crossOrigin = "anonymous";
  const textures = await Promise.all(urls.map((url) => loader.loadAsync(url)));
  for (const texture of textures) {
    texture.colorSpace = THREE.SRGBColorSpace;
    texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
  }
  return textures;
}

Two settings per texture, each with its reason. SRGBColorSpace tells Three.js that the file’s pixels are sRGB-encoded, otherwise the photos come out washed out. Anisotropy at the GPU’s maximum keeps cards seen almost edge-on from sparkling: at that angle, one texel covers a very stretched strip of the screen and isotropic filtering averages garbage.

Cropping

The photos don’t all share the card’s ratio. Rather than resizing them, I crop the way object-fit: cover does, by playing with the texture coordinates. If the image is wider than the card, we only read a centred fraction of its width; otherwise of its height.

// fan.js
function coverMapping(texture, cardAspect) {
  const { width, height } = texture.image;
  const imageAspect = width / height;
  const repeat = new THREE.Vector2(1, 1);
  if (imageAspect > cardAspect) repeat.x = cardAspect / imageAspect;
  else repeat.y = imageAspect / cardAspect;
  const offset = new THREE.Vector2((1 - repeat.x) / 2, (1 - repeat.y) / 2);
  return { repeat, offset };
}

The result is a repeat and an offset that the shader applies to the UVs. The texture itself is never touched, and the same computation would work for any card size.

The material

I don’t use Three.js’s standard materials. Each card has its own ShaderMaterial, but they all share the same source code, so the GPU compiles a single program. The fragment shader just samples the photo at the cropped coordinates:

// material.js — fragment
gl_FragColor = vec4(texture2D(uMap, vUv * uRepeat + uOffset).rgb, 1.0);
#include <colorspace_fragment>

No lighting, no PBR, no cast shadows. The material is DoubleSide because you see the back of the cards on the far side of the ring. The vertex shader has a job too, the bend, but I’ll come back to it in the last section.

The mesh

A single geometry is shared by every card: a PlaneGeometry(1, 1, 24, 1) translated so that x goes from 0 to 1, with its left edge at the origin. The 24 subdivisions along x only exist for the bend. Each mesh is then scaled to the chosen card size.

// fan.js
const geometry = new THREE.PlaneGeometry(1, 1, 24, 1);
geometry.translate(0.5, 0, 0);

for (let i = 0; i < count; i++) {
  const material = createCardMaterial({
    map: textures[i],
    ...coverMapping(textures[i], card.width / card.height),
    bendUniform,
  });
  const mesh = new THREE.Mesh(geometry, material);
  mesh.scale.set(card.width, card.height, 1);
  // ... placement in the ring, next section
}

bendUniform is the same { value: 0 } object for all twelve materials. It’s the same mechanism as the uWindDirection shared by reference in the grass series: it’s what will let me, further down, bend every card with a single write per frame.

Placing the cards in the ring

The most structuring decision is not to put the cards directly in the scene. Each card sits inside a small Group acting as a hinge. The mesh is offset by ringRadius along that group’s local x axis, so its left edge is ringRadius away from the axis, and the group is rotated around the vertical axis by i × 2π / count. All the groups are children of a single root, and that root is what spins.

// fan.js
mesh.position.x = ringRadius;

const pivot = new THREE.Group();
pivot.add(mesh);
root.add(pivot);
pivots.push(pivot);
restAngles.push((i * Math.PI * 2) / count);

The picture is a ring binder lying flat: each card is a page hanging by its left edge from a small central circle and pointing outward, like a spoke.

Scene
└─ root (Group)          rotation.y = spin, rotation.x = tilt
   ├─ pivot 0 (Group)    rotation.y = the card's angle on the ring
   │  └─ mesh 0          shared geometry, position.x = ringRadius
   ├─ pivot 1
   │  └─ mesh 1
   └─ ...

This three-level hierarchy has three advantages:

  • One global rotation. Spinning the whole ring means writing one value on the root. No card needs recomputing.
  • The opening animation becomes trivial. Each hinge interpolates its angle from the closed deck to its resting position. Since every card stays a radial plane, they can only meet on the axis, inside the hole of the ring. No visible intersection, whatever the timing.
  • The bend has a natural anchor. The card will be curved from its hinge, like a page turned too fast.

The opening

The cards start stacked, 0.02 radian apart, and unfold towards restAngles[i].

// fan.js
function applyOpening() {
  opened = true;
  for (let i = 0; i < count; i++) {
    const delay = ((count - 1 - i) / count) * opening.stagger;
    const t = clamp((elapsed - delay) / opening.duration, 0, 1);
    if (t < 1) opened = false;
    pivots[i].rotation.y = lerp(
      i * opening.closedSpread,
      restAngles[i],
      easeOutExpo(t),
    );
  }
}

The easeOutExpo curve gives a brisk start and a soft landing. The card furthest ahead leaves first, each one starting after the previous: the total stagger is 0.7 s and each card takes 1.6 s. The function is called once at construction to set the initial state, then every frame until every card has arrived. The “Replay opening” button in the demo simply resets elapsed to zero.

Motion: rotation, inertia and tilt on drag

The ring’s rotation has a single writer: the tick function called every frame. Pointer events never touch the scene. They accumulate their deltas in variables, and the next frame consumes them in one go. I adopted this rule after noticing that mice and pens fire their events anywhere between 60 and 1,000 Hz: applying each delta directly made the ring visibly jitter.

// fan.js
onDrag(dx, dy) {
  pendingX += dx;
  dragY += dy;
  held = true;
  lastDragAt = performance.now();
}

The drag itself relies only on Pointer Events, so mouse, touch and pen behave identically. setPointerCapture keeps the gesture even if the pointer leaves the canvas, and touch-action: none stops the browser from scrolling instead.

Rotation

Every frame, three sources add up:

  1. Idle rotation, autoSpeed × delta, 0.15 radian per second by default.
  2. The drag, as long as the last pointer event is less than 80 ms old. The ring then follows the finger exactly, and the per-frame speed is remembered.
  3. Inertia, once the finger lifts: the remembered speed is multiplied by 0.94 every frame until it dies out.
// fan.js — tick
const dragging = performance.now() - lastDragAt < 80;
if (dragging) {
  velocity = pendingX * motion.dragSensitivity;
  pendingX = 0;
} else {
  velocity *= motion.damping;
}
const step = motion.autoSpeed * delta + velocity;
spin += step;

The 80 ms threshold solves a concrete problem. There’s no reliable event for “the finger stopped but didn’t lift”. With that delay, a still finger simply cuts the speed to zero, and a finger that moves again picks it back up.

Tilt

A vertical drag tilts the whole ring around the screen’s horizontal axis. Unlike the rotation, the tilt isn’t driven by pointer speed but by the distance travelled since the press, clamped to 0.35 radian and smoothed so it never snaps. Pulling down brings the near edge down, as if rolling the object under your finger. On release, the target goes back to zero and the ring eases back to flat.

// fan.js — tick
const tiltTarget = held
  ? clamp(dragY * motion.tiltSensitivity, -motion.tiltMax, motion.tiltMax)
  : 0;
tilt += (tiltTarget - tilt) * Math.min(1, 8 * delta);
root.rotation.set(tilt, spin, 0);

It’s a detail, but it gives the object a physical presence: you feel you’re holding something rigid.

Bending the cards in the vertex shader

When the ring spins fast, the free edge of each card trails behind the hinge, like paper catching the wind. When it slows down, the cards straighten up with a slight overshoot.

The deformation is done entirely on the GPU. The vertex shader, set aside earlier, moves each vertex along z following a parabola from the hinge:

// material.js — vertex
vec3 p = position;         // x from 0 (hinge) to 1 (free edge)
p.z += uBend * p.x * p.x;

The parabola is the simplest choice that gives a zero tangent at the hinge, so a card that leaves its attachment point perfectly straight. It’s the reason the geometry has 24 subdivisions along x: a two-triangle plane can’t curve.

On the CPU side, the work is minimal. The uBend uniform is the single object shared by every card’s material: one write per frame. Its value follows a damped spring chasing the angular speed:

// fan.js — tick
const angularSpeed = delta > 0 ? step / delta : 0;
const target = clamp(angularSpeed * bend.gain, -bend.max, bend.max);
const dt = Math.min(delta, 1 / 30);
bendVelocity += (target - bendAmount) * bend.stiffness * dt;
bendVelocity *= Math.max(0, 1 - bend.damping * dt);
bendAmount += bendVelocity * dt;
bendUniform.value = bendAmount;

The spring rather than a plain smoothing is what gives the little bounce when you let go of the ring. With a stiffness of 60 and a damping of 9, the cards slightly overshoot their resting position before settling. Lower the damping in the demo to see the cards oscillate several times, or raise the stiffness to make them snap. The time step is clamped to 1/30 s so the spring stays stable after a tab switch or a slowdown.

The sign matters too. Spinning left or right bends the cards one way or the other, since angularSpeed is signed.

This is the version, with a few improvements, that runs in the photographer’s portfolio shown in the video at the top of the article.