THREE.JS GLSL
GRADIENT SHADER CUBE

By Shane Brumback · · Updated · Free Three.js tutorial · Level 1

To color a Three.js cube with a GLSL gradient, give a BoxGeometry a ShaderMaterial whose fragment shader turns gl_FragCoord and a u_time uniform into red, green, and blue sine waves, then advance u_time every frame. The cube spinning behind this page is that exact shader.

A beginner walkthrough of ShaderMaterial, vertex and fragment shaders, and uniforms in Three.js. Live demo and the full copy-paste source below.

✓ FREE Level 1 · Beginner ShaderMaterial GLSL fragment shader Time uniform
See it live

LIVE DEMO

The shader cube sitting on the grass behind this page is a live Three.js scene, with low-poly hills, rocks, trees and drifting clouds. Launch the full-screen demo to drag to orbit and scroll to zoom while the GLSL gradient shifts across every face. Launch asks for a free Google sign-in first. Press Esc or Exit to return.

Orbit: drag · Zoom: scroll · Esc to exit

READY FOR A REAL TERRAIN SHADER?

This Level 1 cube is the first step. The Level 3 premium Terrain LOD tutorial blends sand, grass, rock and snow by height and slope in an onBeforeCompile shader, with LOD skirts, worker chunks and grass. Members unlock the full code; sign in to reveal it.

Three.js terrain LOD and splat shader premium tutorial
See the Level 3 Tutorial

What Is a Shader?

Three.js is a JavaScript library that wraps WebGL, the browser API for GPU accelerated graphics. Most of the time you pick a built-in material such as MeshStandardMaterial. When you want full control over how pixels look, you write shaders: small programs in the OpenGL Shading Language (GLSL) that run on the graphics card.

A vertex shader runs once per corner and decides where it lands on screen. A fragment shader runs once per pixel and decides its color. New to Three.js? Start with the spinning cube starter or rendering a 3D cube.

Code Breakdown

1. Set up a sunny sky, camera and shadows

scene.background = new THREE.Color(0x9fd3f0);
scene.fog = new THREE.Fog(0x9fd3f0, 30, 90);
renderer.shadowMap.enabled = true;
scene.add(new THREE.HemisphereLight(0xcfeaff, 0x5a7a3a, 1.1));
const sun = new THREE.DirectionalLight(0xfff1d6, 2.2);
sun.position.set(10, 16, 6);
sun.castShadow = true;

In plain words: paint the sky light blue, fade far things into fog, and add two lights: a soft sky glow from above and a warm sun that casts shadows.

2. Create a ShaderMaterial with a time uniform

const material = new THREE.ShaderMaterial({
  uniforms: { u_time: { value: 0.0 } },
  vertexShader, fragmentShader
});

In plain words: uniforms are values JavaScript shares with the shader. u_time is the clock that drives the animation.

3. Project vertices in the vertex shader

void main() {
  gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}

In plain words: Three.js hands the shader position, modelViewMatrix and projectionMatrix, so this one line puts every corner of the cube in the right spot on screen.

4. Paint a gradient in the fragment shader

uniform float u_time;
void main() {
  gl_FragColor = vec4(
    sin(u_time + gl_FragCoord.x * 0.01) * 0.5 + 0.5,
    sin(u_time + gl_FragCoord.y * 0.01) * 0.5 + 0.5,
    sin(u_time) * 0.5 + 0.5,
    1.0);
}

In plain words: each color channel is a sine wave squeezed from -1..1 into 0..1. Red changes across the screen, green changes up and down, and blue pulses over time.

5. Sit the cube on the grass

const cube = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), material);
cube.position.y = 1.6;
cube.castShadow = true;
scene.add(cube);

In plain words: make an even 2 x 2 x 2 box so it stays a true cube, lift it just above the ground so it can spin freely, and let it cast a shadow on the grass.

6. Build the low-poly landscape

const flat = (color) => new THREE.MeshStandardMaterial({ color, flatShading: true });
const ground = new THREE.Mesh(groundGeo, flat(0x6fae4a));     // bumpy grass plane
const hill = new THREE.Mesh(new THREE.IcosahedronGeometry(9, 1), flat(0x5f9a3f));
const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(0.5, 0), flat(0x8a8f96));
const cone = new THREE.Mesh(new THREE.ConeGeometry(1.1, 1.4, 7), flat(0x2f7d3b)); // tree layer

In plain words: flatShading gives every face one solid color, which creates the faceted low-poly look. Squashed icosahedrons become hills, dodecahedrons become rocks, and stacked cones on a trunk become trees. White icosahedron puffs make clouds.

7. Advance time in the render loop

material.uniforms.u_time.value += 0.05;
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
clouds.forEach((c) => { c.position.x += 0.01; });
renderer.render(scene, camera);

In plain words: every frame, nudge the shader clock so the waves move, spin the cube a little, and drift the clouds. For more shader motion ideas see animating spheres with fragment shaders, or make the cube clickable with raycaster selection.

The Full Code

This is one complete HTML file (Three.js 0.160.0 from unpkg, no build tools, no models or textures). Save it as index.html and open it, or press Launch Full Code to run it in a new window. The original cube is also in this GitHub Gist.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Three.js GLSL Gradient Shader Cube on a Low-Poly Landscape</title>
<script type="importmap">
{"imports":{"three":"https://unpkg.com/three@0.160.0/build/three.module.js","three/addons/":"https://unpkg.com/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';

const isMobile = matchMedia('(max-width: 768px)').matches;

// Scene, sky color and soft distance fog
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9fd3f0);
scene.fog = new THREE.Fog(0x9fd3f0, 30, 90);

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

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, isMobile ? 1.5 : 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.style.margin = '0';
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 1.2, 0);
controls.enableDamping = true;
controls.autoRotate = true;
controls.autoRotateSpeed = 0.6;
controls.maxPolarAngle = Math.PI * 0.47;
controls.minDistance = 5;
controls.maxDistance = 30;

// Soft sky light plus a warm sun that casts shadows
scene.add(new THREE.HemisphereLight(0xcfeaff, 0x5a7a3a, 1.1));
const sun = new THREE.DirectionalLight(0xfff1d6, 2.2);
sun.position.set(10, 16, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(isMobile ? 1024 : 2048, isMobile ? 1024 : 2048);
Object.assign(sun.shadow.camera, { left: -16, right: 16, top: 16, bottom: -16, near: 1, far: 50 });
sun.shadow.bias = -0.0005;
scene.add(sun);

// The GLSL gradient shader cube (the hero)
const material = new THREE.ShaderMaterial({
  uniforms: { u_time: { value: 0.0 } },
  vertexShader: `
    void main() {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }`,
  fragmentShader: `
    uniform float u_time;
    void main() {
      gl_FragColor = vec4(
        sin(u_time + gl_FragCoord.x * 0.01) * 0.5 + 0.5,
        sin(u_time + gl_FragCoord.y * 0.01) * 0.5 + 0.5,
        sin(u_time) * 0.5 + 0.5,
        1.0);
    }`
});
const cube = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), material);
cube.position.y = 1.6;
cube.castShadow = true;
scene.add(cube);

// Grassy ground with gentle low-poly bumps
const flat = (color) => new THREE.MeshStandardMaterial({ color, flatShading: true, roughness: 0.95 });
const groundGeo = new THREE.PlaneGeometry(160, 160, 48, 48);
groundGeo.rotateX(-Math.PI / 2);
const gp = groundGeo.attributes.position;
for (let i = 0; i < gp.count; i++) {
  const x = gp.getX(i), z = gp.getZ(i), d = Math.hypot(x, z);
  if (d > 7) gp.setY(i, (Math.sin(x * 0.35) + Math.cos(z * 0.3)) * 0.25 * Math.min(1, (d - 7) / 6));
}
groundGeo.computeVertexNormals();
const ground = new THREE.Mesh(groundGeo, flat(0x6fae4a));
ground.receiveShadow = true;
scene.add(ground);

// Low-poly hills in the distance
[[-20, -26, 10, 0x5f9a3f], [6, -34, 13, 0x6aa647], [26, -20, 9, 0x588f3a], [-32, 4, 10, 0x64a043]].forEach(([x, z, r, c]) => {
  const hill = new THREE.Mesh(new THREE.IcosahedronGeometry(r, 1), flat(c));
  hill.position.set(x, -r * 0.45, z);
  hill.scale.y = 0.6;
  hill.receiveShadow = true;
  scene.add(hill);
});

// Rocks: squashed low-detail dodecahedrons
const rockMat = flat(0x8a8f96);
[[3.2, 1.8, 0.5], [-2.8, 2.6, 0.7], [-1.6, -3.4, 0.4], [4.5, -2.5, 0.6], [1.4, 4.2, 0.35]].forEach(([x, z, s]) => {
  const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(s, 0), rockMat);
  rock.position.set(x, s * 0.4, z);
  rock.scale.y = 0.7;
  rock.rotation.set(x, z, 0);
  rock.castShadow = rock.receiveShadow = true;
  scene.add(rock);
});

// Trees: a brown trunk and stacked green cones
const trunkMat = flat(0x7a5233), leafMat = flat(0x2f7d3b);
function tree(x, z, s) {
  const t = new THREE.Group();
  const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.15, 0.22, 1, 6), trunkMat);
  trunk.position.y = 0.5;
  t.add(trunk);
  for (let i = 0; i < 3; i++) {
    const cone = new THREE.Mesh(new THREE.ConeGeometry(1.1 - i * 0.25, 1.4, 7), leafMat);
    cone.position.y = 1.4 + i * 0.75;
    t.add(cone);
  }
  t.traverse((m) => { m.castShadow = true; });
  t.position.set(x, 0, z);
  t.scale.setScalar(s);
  scene.add(t);
}
[[-5, -4, 1.2], [-7, 1, 1], [6, -6, 1.3], [-3, -9, 1.5], [9, -1, 1], [2, -11, 1.4], [-10, -7, 1.6], [12, -10, 1.7]].forEach((a) => tree(...a));

// Soft low-poly clouds that drift across the sky
const cloudMat = new THREE.MeshStandardMaterial({ color: 0xffffff, flatShading: true, roughness: 1 });
const clouds = [];
[[-14, 11, -22], [4, 13, -30], [20, 12, -18], [-26, 12, -6]].forEach(([x, y, z]) => {
  const c = new THREE.Group();
  [[0, 0, 2.2], [2.2, -0.3, 1.6], [-2.1, -0.4, 1.5], [0.8, 0.9, 1.4]].forEach(([px, py, r]) => {
    const puff = new THREE.Mesh(new THREE.IcosahedronGeometry(r, 0), cloudMat);
    puff.position.set(px, py, 0);
    c.add(puff);
  });
  c.position.set(x, y, z);
  scene.add(c);
  clouds.push(c);
});

// Animate: advance the shader clock, spin the cube, drift the clouds
function render() {
  requestAnimationFrame(render);
  controls.update();
  material.uniforms.u_time.value += 0.05;
  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;
  clouds.forEach((c) => { c.position.x += 0.01; if (c.position.x > 45) c.position.x = -45; });
  renderer.render(scene, camera);
}
render();

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

Frequently Asked Questions

What is a GLSL gradient shader in Three.js?

It is a custom fragment shader, written in the OpenGL Shading Language, that computes a color for every pixel of a mesh. In this demo the red, green, and blue channels come from sine waves of the screen position and time, which produces a smooth moving gradient.

How do you apply a custom shader to a cube in Three.js?

Create a BoxGeometry, then a ShaderMaterial with a vertexShader and fragmentShader string, and pass both to a Mesh. The vertex shader projects each corner with projectionMatrix and modelViewMatrix, and the fragment shader outputs gl_FragColor.

How do you animate a shader with a time uniform?

Declare a uniform such as u_time in the material, read it in the fragment shader, and add a small amount to material.uniforms.u_time.value every frame in the render loop. The GPU sees the new value on the next draw.

Why does the gradient use gl_FragCoord?

gl_FragCoord holds the pixel position on screen, so the colors are tied to the viewport rather than the cube surface. That gives a shimmering, screen space look as the cube spins. Pass UV coordinates through a varying if you want the gradient to stick to each face.

Do lights affect a ShaderMaterial?

No. A basic ShaderMaterial ignores scene lights unless you add lighting math yourself or enable the lights uniforms. The gradient cube looks the same in full sun or in shade (the grass, rocks and trees around it are lit, the shader cube is not), which keeps the shader easy to read.

Which Three.js version does this demo use?

The demo loads Three.js 0.160 as an ES module through an import map, with OrbitControls from the examples addons folder. No build tools are needed, so you can copy the code into one HTML file and open it in a browser.

How do you build the low-poly landscape around the cube?

The ground is a PlaneGeometry with a few vertices nudged up and down, hills are squashed IcosahedronGeometry shapes, rocks are DodecahedronGeometry, trees are a CylinderGeometry trunk with stacked ConeGeometry layers, and clouds are white icosahedron puffs. Every one uses MeshStandardMaterial with flatShading: true, which gives the faceted low-poly look. A HemisphereLight and a shadow-casting DirectionalLight provide the soft outdoor lighting.

Play It and Keep Learning

Shaders like this one color the effects in Super Soldier Battle, free in your browser. Browse every Three.js tutorial, read the articles, or search the site.

Need Three.js shader or WebGL work? I take freelance and contract work: contact me.

Play Game