ANIMATED SPHERES
& FRAGMENT SHADERS

Float a calm cloud of glossy 3D spheres over a slowly rippling GLSL fragment-shader floor in the browser with Three.js — real GPU shader animation, beginner friendly, no extra libraries.

✓ FREE Level 1 · Beginner GLSL fragment shader MeshPhysicalMaterial
See it live

LIVE DEMO

The glossy spheres drifting over the rippling shader floor behind this page are a live Three.js scene. Drag the empty background to orbit it, or launch the full-screen demo to drag to orbit and scroll to zoom. Launch asks for a free Google sign-in first. Press Esc or Exit to return.

Free Google sign-in · Orbit: drag · Zoom: scroll · Esc to exit

Introduction

This free tutorial combines two of the most rewarding Three.js techniques: animating many objects and writing your own GLSL shader. You will float 32 glossy pastel spheres on slow, gently bobbing orbits and lay them over a floor painted by a live fragment shader that ripples softly outward over time.

The shader runs on the GPU, once per pixel, driven by a single time uniform set from a clock each frame. Keeping the numbers next to time small is what makes it calm instead of flashy. It is the same technique behind gradients, water, fire, and glow effects. Copy it, paste it, and it runs.

Frequently Asked Questions

What is a fragment shader in Three.js?

A fragment shader is a small GLSL program that runs on the GPU once for every pixel of a surface, deciding that pixel's final color. In Three.js you supply it through a ShaderMaterial. Because it runs per-pixel on the GPU, you can create smooth animated gradients, patterns, and effects that would be far too slow to compute in JavaScript.

How do you animate a GLSL shader in Three.js?

Pass a uniform such as time into the ShaderMaterial, then set it every frame from a THREE.Clock (material.uniforms.time.value = clock.elapsedTime). Inside the fragment shader, use that time value with sin(), mix() and smoothstep() to move ripples and blend colors. Multiplying time by a small number like 0.15 keeps the animation slow and soothing.

What is the difference between a vertex and a fragment shader?

A vertex shader runs once per vertex and positions the geometry (it outputs gl_Position). A fragment shader runs once per pixel that the geometry covers and outputs the pixel color (gl_FragColor). A ShaderMaterial in Three.js needs both: the vertex shader places the shape, the fragment shader paints it.

How do you make many 3D objects move smoothly in Three.js?

Store a few numbers on each object (orbit radius, speed, bob height, phase) and use real elapsed time from a THREE.Clock to place it each frame with cos(), sin() for the circle and sin() again for a gentle up-and-down bob. Because sin() eases in and out, the motion looks graceful. Reusing one shared SphereGeometry keeps it fast.

Is this Three.js shader tutorial free?

Yes. This is a completely free tutorial. The full source code is on the page and you can copy it. Interacting with the live demo of calm spheres over a rippling shader floor requires a quick, free Google sign-in, but no paid membership is needed.

Step-by-Step Code Breakdown

Every excerpt below is copied exactly from the full code further down.

1. Scene, camera and renderer

In plain words: we make an empty 3D world, a camera to look at it, and a renderer that draws it. A dark background and fog let distant things melt into the night, and ACES tone mapping keeps colors soft instead of harsh.

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0c1527);
scene.fog = new THREE.Fog(0x0c1527, 18, 48);

const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 200);
camera.position.set(0, 4.5, 14);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.0;
document.body.appendChild(renderer.domElement);

2. Write the fragment shader floor

In plain words: a fragment shader is a tiny program that runs once for every pixel and decides its color. Ours measures how far each pixel is from the middle, makes slow rings with sin(), blends three calm colors, and fades to black at the edges. Small numbers next to time (0.6, 0.15) keep it slow and gentle.

const floorMaterial = new THREE.ShaderMaterial({
  uniforms: {
    time:   { value: 0 },
    deep:   { value: new THREE.Color(0x1a2c46) },  // dark navy
    mid:    { value: new THREE.Color(0x2f7380) },  // muted teal
    glow:   { value: new THREE.Color(0x9a88c8) }   // dusty violet
  },
  vertexShader: `
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: `
    uniform float time;
    uniform vec3 deep, mid, glow;
    varying vec2 vUv;
    void main() {
      vec2 p = (vUv - 0.5) * 16.0;          // centre the pattern
      float d = length(p);                  // distance from the middle
      float ripple = sin(d * 2.2 - time * 0.6) * 0.5 + 0.5;
      float flow = sin(p.x * 0.7 + time * 0.15) * sin(p.y * 0.6 - time * 0.12) * 0.5 + 0.5;
      vec3 color = mix(deep, mid, flow * 0.8);
      color = mix(color, glow, ripple * 0.35 * smoothstep(4.0, 0.0, d));
      color = mix(deep * 0.35, color, smoothstep(6.0, 0.5, d)); // fade into the night
      gl_FragColor = vec4(color, 1.0);
      #include <colorspace_fragment>
    }
  `
});
const floor = new THREE.Mesh(new THREE.PlaneGeometry(80, 80), floorMaterial);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2;
scene.add(floor);

3. Add gentle lights

In plain words: a sky-and-ground light fills everything softly, and one warm light from above gives the spheres a highlight.

scene.add(new THREE.HemisphereLight(0xbcd4ff, 0x1a1530, 0.6));
const key = new THREE.DirectionalLight(0xfff1e0, 1.4);
key.position.set(6, 10, 8);
scene.add(key);

4. Create a calm cloud of glossy spheres

In plain words: we make 32 spheres from one shared shape, color them from a five-color pastel palette, and give each a glossy clear-coat with a faint glow. Each one remembers its own orbit size, speed and bob so they all move a little differently.

const palette = [0x8ecfc9, 0x9bb7e0, 0xc3b1e1, 0xf2c4b0, 0xece4d4];
const sphereGeo = new THREE.SphereGeometry(1, 48, 32);
const spheres = [];
for (let i = 0; i < 32; i++) {
  const color = palette[i % palette.length];
  const mat = new THREE.MeshPhysicalMaterial({
    color, roughness: 0.25, metalness: 0.0,
    clearcoat: 1.0, clearcoatRoughness: 0.15,
    emissive: color, emissiveIntensity: 0.08   // a subtle inner glow
  });
  const s = new THREE.Mesh(sphereGeo, mat);
  s.scale.setScalar(0.25 + Math.random() * 0.4);
  s.userData = {
    radius: 2 + Math.random() * 5,          // orbit size
    angle:  Math.random() * Math.PI * 2,    // where it starts
    speed:  0.05 + Math.random() * 0.08,    // radians per second (slow!)
    height: Math.random() * 4,              // resting height
    bob:    0.2 + Math.random() * 0.3,      // how far it floats up and down
    phase:  Math.random() * Math.PI * 2
  };
  scene.add(s);
  spheres.push(s);
}

5. Animate smoothly with real time

In plain words: a Clock tells us how many seconds passed, so motion is the same speed on every computer. Each sphere slides a little around its circle and floats up and down with sin(), which eases in and out naturally. We also hand the time to the shader so the floor ripples.

const clock = new THREE.Clock();
function animate() {
  requestAnimationFrame(animate);
  const dt = Math.min(clock.getDelta(), 0.05);
  const t = clock.elapsedTime;
  for (const s of spheres) {
    const u = s.userData;
    u.angle += u.speed * dt;
    s.position.set(
      Math.cos(u.angle) * u.radius,
      u.height + Math.sin(t * 0.5 + u.phase) * u.bob,  // eased bobbing
      Math.sin(u.angle) * u.radius
    );
  }
  floorMaterial.uniforms.time.value = t;   // drive the shader animation
  controls.update();
  renderer.render(scene, camera);
}
animate();

The Full Code

Paste this into a file named index.html and open it in any modern browser.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Three.js Calm Spheres &amp; Fragment Shader</title>
  <style> body { margin: 0; background: #0c1527; overflow: hidden; } </style>
  <script type="importmap">
  {
    "imports": {
      "three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
      "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
    }
  }
  </script>
</head>
<body>
<script type="module">
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';

  // --- 1. Scene, camera, renderer ---
  const scene = new THREE.Scene();
  scene.background = new THREE.Color(0x0c1527);
  scene.fog = new THREE.Fog(0x0c1527, 18, 48);

  const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 200);
  camera.position.set(0, 4.5, 14);

  const renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
  renderer.setSize(innerWidth, innerHeight);
  renderer.toneMapping = THREE.ACESFilmicToneMapping;
  renderer.toneMappingExposure = 1.0;
  document.body.appendChild(renderer.domElement);

  // Soft studio reflections for the glossy spheres
  const pmrem = new THREE.PMREMGenerator(renderer);
  scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;

  // --- Orbit controls: drag (mouse or touch) to orbit. Zoom is off and
  // touch-action stays pan-y, so vertical swipes still scroll the page on phones.
  const controls = new OrbitControls(camera, renderer.domElement);
  controls.target.set(0, 1, 0);
  controls.enableDamping = true;
  controls.enableZoom = false;
  controls.enablePan = false;
  controls.autoRotate = true;
  controls.autoRotateSpeed = 0.3;
  renderer.domElement.style.touchAction = 'pan-y';

  // --- 2. The fragment shader floor (slow, soft ripples) ---
  const floorMaterial = new THREE.ShaderMaterial({
    uniforms: {
      time:   { value: 0 },
      deep:   { value: new THREE.Color(0x1a2c46) },  // dark navy
      mid:    { value: new THREE.Color(0x2f7380) },  // muted teal
      glow:   { value: new THREE.Color(0x9a88c8) }   // dusty violet
    },
    vertexShader: `
      varying vec2 vUv;
      void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
      }
    `,
    fragmentShader: `
      uniform float time;
      uniform vec3 deep, mid, glow;
      varying vec2 vUv;
      void main() {
        vec2 p = (vUv - 0.5) * 16.0;          // centre the pattern
        float d = length(p);                  // distance from the middle
        float ripple = sin(d * 2.2 - time * 0.6) * 0.5 + 0.5;
        float flow = sin(p.x * 0.7 + time * 0.15) * sin(p.y * 0.6 - time * 0.12) * 0.5 + 0.5;
        vec3 color = mix(deep, mid, flow * 0.8);
        color = mix(color, glow, ripple * 0.35 * smoothstep(4.0, 0.0, d));
        color = mix(deep * 0.35, color, smoothstep(6.0, 0.5, d)); // fade into the night
        gl_FragColor = vec4(color, 1.0);
        #include <colorspace_fragment>
      }
    `
  });
  const floor = new THREE.Mesh(new THREE.PlaneGeometry(80, 80), floorMaterial);
  floor.rotation.x = -Math.PI / 2;
  floor.position.y = -2;
  scene.add(floor);

  // --- 3. Gentle lights ---
  scene.add(new THREE.HemisphereLight(0xbcd4ff, 0x1a1530, 0.6));
  const key = new THREE.DirectionalLight(0xfff1e0, 1.4);
  key.position.set(6, 10, 8);
  scene.add(key);

  // --- 4. A calm cloud of glossy spheres ---
  const palette = [0x8ecfc9, 0x9bb7e0, 0xc3b1e1, 0xf2c4b0, 0xece4d4];
  const sphereGeo = new THREE.SphereGeometry(1, 48, 32);
  const spheres = [];
  for (let i = 0; i < 32; i++) {
    const color = palette[i % palette.length];
    const mat = new THREE.MeshPhysicalMaterial({
      color, roughness: 0.25, metalness: 0.0,
      clearcoat: 1.0, clearcoatRoughness: 0.15,
      emissive: color, emissiveIntensity: 0.08   // a subtle inner glow
    });
    const s = new THREE.Mesh(sphereGeo, mat);
    s.scale.setScalar(0.25 + Math.random() * 0.4);
    s.userData = {
      radius: 2 + Math.random() * 5,          // orbit size
      angle:  Math.random() * Math.PI * 2,    // where it starts
      speed:  0.05 + Math.random() * 0.08,    // radians per second (slow!)
      height: Math.random() * 4,              // resting height
      bob:    0.2 + Math.random() * 0.3,      // how far it floats up and down
      phase:  Math.random() * Math.PI * 2
    };
    scene.add(s);
    spheres.push(s);
  }

  // --- 5. Animate with real time so motion stays smooth ---
  const clock = new THREE.Clock();
  function animate() {
    requestAnimationFrame(animate);
    const dt = Math.min(clock.getDelta(), 0.05);
    const t = clock.elapsedTime;
    for (const s of spheres) {
      const u = s.userData;
      u.angle += u.speed * dt;
      s.position.set(
        Math.cos(u.angle) * u.radius,
        u.height + Math.sin(t * 0.5 + u.phase) * u.bob,  // eased bobbing
        Math.sin(u.angle) * u.radius
      );
    }
    floorMaterial.uniforms.time.value = t;   // drive the shader animation
    controls.update();
    renderer.render(scene, camera);
  }
  animate();

  addEventListener('resize', () => {
    camera.aspect = innerWidth / innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(innerWidth, innerHeight);
  });
</script>
</body>
</html>

What To Try Next

  • Try a bigger number in sin(d * 2.2 - time * 0.6) to see tighter, faster rings, then dial it back.
  • Feed the mouse position in as a uniform and let the shader colors react to the cursor.
  • Change the three deep, mid and glow uniform colors to give the floor a sunset or ocean mood.
  • Use InstancedMesh to push the sphere count into the thousands.