Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Shaders and Post-processing

Shader Material Basics: GLSL in Three.js

Write your first Three.js shaders: vertex and fragment stages, uniforms, varyings, built-in attributes, ShaderMaterial, animated patterns and a toon shader, with live examples.

Built-in materials cover most needs, but sooner or later you want an effect they cannot give: a hologram, animated water, a dissolve, a stylized outline. For that you write your own shader: a small program that runs on the GPU, once per vertex and once per pixel, in a language called GLSL. Three.js lets you plug your shader into the normal pipeline with ShaderMaterial, so meshes, cameras, the scene graph and animation keep working.

Shaders are a big topic, so this lesson sticks to the essentials: the two stages, the three kinds of data, and three runnable shaders that grow in complexity.

The two stages

Every shader program has a vertex shader and a fragment shader.

What the GPU runs

Vertex shader Once per vertex: where on screen?
Rasterizer Fills triangles with fragments
Fragment shader Once per pixel: which color?

Values from vertices are interpolated across each triangle before the fragment shader sees them.

1 / 2

The vertex shader's main job is to set gl_Position, the final clip-space position of the vertex. The fragment shader's main job is to set the output color. Everything else is plumbing.

A minimal ShaderMaterial

JavaScript
const material = new THREE.ShaderMaterial({
  uniforms: {
    uColor: { value: new THREE.Color('#ff7a18') }
  },
  vertexShader: /* glsl */ `
    varying vec2 vUv;
    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: /* glsl */ `
    uniform vec3 uColor;
    varying vec2 vUv;
    void main() {
      gl_FragColor = vec4(uColor * vUv.x, 1.0);
    }
  `
});

ShaderMaterial automatically declares a set of helpers for you in both shaders, so you do not write them:

Name Kind Meaning
position, normal, uv attribute Vertex data from the geometry
modelMatrix uniform Object to world
viewMatrix uniform World to camera
modelViewMatrix uniform Object to camera
projectionMatrix uniform Camera to clip space (perspective)
normalMatrix uniform Rotates normals correctly (mat3)
cameraPosition uniform Camera in world space

RawShaderMaterial is the same without this automatic code: you declare every attribute, uniform and precision yourself. Use ShaderMaterial unless you have a reason not to.

The line projectionMatrix * modelViewMatrix * vec4(position, 1.0) is the whole 3D pipeline in one expression: the vertex is moved by the object transform, then the camera transform, then projected. If you skip it and write gl_Position = vec4(position, 1.0), the geometry is drawn directly in screen space, which is what full-screen effects do.

GLSL in five minutes

GLSL is a C-like language with built-in vector types.

  • Types: float, int, bool, vec2, vec3, vec4, mat3, mat4, sampler2D. Floats need a decimal point: 1.0, not 1.
  • Swizzling: color.rgb, p.xy, v.zyx; vector arithmetic works component-wise: vec3(1.0) * 0.5.
  • Useful functions: mix(a, b, t) (lerp), clamp, step(edge, x) (0 or 1), smoothstep(e0, e1, x), fract, floor, abs, sin, length, distance, dot, normalize, pow, texture2D or texture.
  • uv runs from 0 to 1 across a face; many patterns are written as functions of uv.
  • There is no print. To debug, output the value as a color and look at it.

Your first shader: a gradient with uniforms

A uniform is a value you set from JavaScript that every vertex and fragment sees. You change it at runtime through material.uniforms.name.value.

A two-color gradient driven by uniforms

The sphere's UVs run bottom to top, so vUv.y blends pink at the bottom to yellow at the top. Uniforms prefixed with u and varyings prefixed with v is a common naming habit that keeps shaders readable.

Colors set through THREE.Color in a uniform are in the renderer's working (linear) color space. The output of a raw ShaderMaterial is not converted to sRGB unless you add #include <colorspace_fragment> at the end of the fragment shader, which is why custom colors can look slightly different from MeshBasicMaterial ones. Add the include when you need colors to match built-in materials exactly.

Animated patterns with time

A shader has no clock of its own; you pass time in as a uniform. The next example draws on a flat plane with a fragment shader only: concentric rings that move, a circle mask made with smoothstep, and a color palette that changes with time.

Rings, masks and time in a fragment shader

This is the "full-screen quad" trick that online shader playgrounds use: output the plane's own x and y as gl_Position and do all the work in the fragment shader. Notice there are no lights or textures: the colors are pure math.

Shading with normals: a toon shader

To react to light, a shader needs the surface normal and a light direction. The vertex shader sends the normal to the fragment shader as a varying, and the fragment shader computes brightness with the dot product: dot(normal, lightDir) is 1 when the surface faces the light and falls to 0 (and below) as it turns away. Quantizing that value into a few steps gives a cartoon look.

A toon (cel) shader

The light direction is fixed in view space here (relative to the camera), because normalMatrix produces view-space normals. For a world-space light, send mat3(modelMatrix) * normal from the vertex shader instead and keep the uniform in world coordinates. This is the kind of detail that makes shaders tricky: always ask "in which space is this vector?"

Updating, debugging and good habits

  • Uniforms: change material.uniforms.x.value; do not recreate the material. Color, Vector2/3/4, Matrix, Texture and numbers are all accepted.
  • Defines and includes: #include <common> and friends pull in Three.js chunks (fog, color space, lights) so your shader can borrow built-in behavior; add fog: true and the fog chunks for fog support.
  • Transparency: set transparent: true and output alpha; set side: THREE.DoubleSide if you need to see back faces.
  • Compile errors appear in the browser console with line numbers relative to the shader string; the first line you see in the message is usually the real mistake (a missing semicolon, an int used where a float was required).
  • Precision: use precision highp float; in RawShaderMaterial; ShaderMaterial handles it for you.
  • Debug by coloring: gl_FragColor = vec4(vUv, 0.0, 1.0); or vec4(normal * 0.5 + 0.5, 1.0) shows you what the data really is.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which stage runs once per vertex and must set gl_Position?

    The vertex shader transforms each vertex into clip space by writing gl_Position. The fragment shader then colors pixels.
  2. 2. How does a value get from the vertex shader to the fragment shader?

    A varying declared in both shaders is written per vertex and arrives interpolated per fragment.
  3. 3. How do you animate a shader over time?

    GLSL has no clock. Pass the time in through a uniform and read it in the shader.
  4. 4. What does ShaderMaterial add compared to RawShaderMaterial?

    ShaderMaterial prepends declarations such as modelViewMatrix and position; RawShaderMaterial needs you to write them.

Summary

  • A shader has a vertex stage (positions) and a fragment stage (colors); attributes are per vertex, uniforms are shared, varyings are interpolated between the stages.
  • ShaderMaterial plugs custom GLSL into Three.js and provides the standard matrices and attributes.
  • Pass time and settings through uniforms; update material.uniforms.x.value per frame.
  • A full-screen quad (position written directly as gl_Position) is ideal for pure-math fragment effects.
  • Lighting is mostly dot(normal, lightDir); always track which coordinate space a vector lives in.

Next: Vertex Shaders, Displacement and onBeforeCompile