three.js Custom Shaders (GLSL)

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

three.js ships dozens of ready-made materials, but sooner or later a project needs a look that none of them gives: a cover that ripples, a book that glows at its edges, a shelf that sways in a draught. The WebGLRenderer offers two ways to get there. You can write a complete shader pair and hand it to ShaderMaterial or RawShaderMaterial, or you can keep a built-in material such as MeshStandardMaterial (so lights, shadows, fog, skinning and instancing keep working) and patch a few lines of its source with onBeforeCompile. This page covers both, with the options each one takes, the traps that waste afternoons, and the limits: custom GLSL is a WebGLRenderer feature, and the new WebGPURenderer replaces it with TSL.

The facts were checked in November 2026 against three.js r187 (npm three@0.187.0), the baseline of this sub-section. The code is ES modules built with Vite (see Getting Started with three.js) and runs in any browser with WebGL 2, which is every evergreen browser; WebGLRenderer has not supported WebGL 1 since r163, so all shaders here are compiled as GLSL ES 3.00 under the hood even when you write the older syntax. For the underlying shader language see GLSL ES 1.00 and 3.00; for the generic idea of uniforms, attributes and varyings see Shading Languages Landscape.

In the Bookshelf three.js track this page sits between the PBR shelf and the post-processing step: the first example gives a book cover a wobble driven by time, the second makes the whole shelf sway without losing its PBR look. The glowing title that appears later is built with TSL on the WebGPU path, see WebGPURenderer and TSL, and the bloom that makes it shine is in Post-processing.

Choosing between ShaderMaterial, RawShaderMaterial and onBeforeCompile

Two columns comparing ShaderMaterial, which prepends matrix uniforms and position, normal and uv attributes, with RawShaderMaterial, which prepends nothing
Figure 1. What each custom-shader route gives you and what it leaves to you
Route What three.js adds for you Use it when

ShaderMaterial

A prefix with precision, the matrix and camera uniforms, the standard attributes, the #define lines for options you switch on (fog, clipping, vertex colours), and the #include expansion.

You want a completely own look, with your own uniforms, and no lighting model from three.js.

RawShaderMaterial

Nothing: your text goes to the driver as written (apart from the #version handling you request through glslVersion).

You port a shader from another project, or you want full control of every declaration, or you want to measure exactly what is compiled.

MeshStandardMaterial (or another built-in) plus onBeforeCompile

All of the built-in shader, with lights, shadows, tone mapping, fog, skinning, morph targets and instancing intact.

You want the standard PBR look and a small change to the geometry or colour: wind, a dissolve, a hologram edge.

A simple rule: if the effect has to be lit like the rest of the scene, patch a built-in material; if it ignores lights (a hologram, an outline, a debug view, a procedural background) write a ShaderMaterial. RawShaderMaterial is the exception, for the cases above.

ShaderMaterial in detail

The constructor takes an object of parameters; every one can also be set as a property afterwards.

Parameter Meaning

uniforms

An object whose keys are uniform names and whose values are objects with a value property: { uTime: { value: 0 } }. The object is read every frame, so changing material.uniforms.uTime.value is all it takes to animate.

vertexShader, fragmentShader

The GLSL source strings. The vertex shader must write gl_Position; the fragment shader writes gl_FragColor (or the GLSL3 output).

defines

An object of preprocessor macros: { USE_BORDER: '', STEPS: 8 } becomes #define USE_BORDER and #define STEPS 8. Changing a define forces a recompile, so treat them as configuration, not animation.

glslVersion

null (the default, legacy syntax) or THREE.GLSL3. With GLSL3 the shader is compiled as #version 300 es and you may use in, out, texture() and the other ES 3.00 keywords. For ShaderMaterial three.js maps the old names (attribute, varying, texture2D, gl_FragColor) onto the new ones, so both styles compile; for RawShaderMaterial you write the #version line and the syntax yourself.

extensions

An object of booleans that request GLSL extensions where the feature is not core, such as clipCullDistance or multiDraw. Derivatives, explicit LOD and gl_FragDepth are core in WebGL 2 and need no switch.

lights

false by default. When true, three.js uploads the light uniforms, which you must declare by merging UniformsLib.lights into your uniforms. Rarely worth it: if you need lights, patch a built-in material.

fog, clipping

false by default. true merges the matching uniforms and defines so that #include <fog_vertex> and the clipping chunks work.

transparent, blending, depthWrite, depthTest, side, wireframe

The ordinary Material state; a custom shader does not change how three.js sorts and blends. A shader that writes alpha below 1 still needs transparent: true.

uniformsNeedUpdate

Set it to true after you change the length or type of a uniform array so that the renderer rebuilds its upload; changing a plain value never needs it.

Built-in uniforms and attributes

ShaderMaterial declares these for you, in both shaders where they apply:

Name Type Meaning

modelMatrix

mat4

Object space to world space.

modelViewMatrix

mat4

Object space to view (camera) space.

projectionMatrix

mat4

View space to clip space.

viewMatrix

mat4

World space to view space.

normalMatrix

mat3

Inverse transpose of the upper 3 by 3 of modelViewMatrix; use it to move normals to view space.

cameraPosition

vec3

The camera position in world space.

position, normal, uv

vec3, vec3, vec2

The geometry attributes of those names (vertex shader only). Any other attribute you add to the BufferGeometry can be used after you declare it yourself.

The matrix chain is the one explained in Coordinate Spaces and Transforms: \( p_{ clip } = P \cdot V \cdot M \cdot p \), which the first line of nearly every three.js vertex shader writes as projectionMatrix * modelViewMatrix * vec4( position, 1.0 ). With InstancedMesh and BatchedMesh the instance transform is applied through an #include chunk; a hand-written ShaderMaterial that skips those chunks draws every instance in the same place.

Uniform value types

GLSL type JavaScript value

float, int, bool

Number (or Boolean)

vec2, vec3, vec4

Vector2, Vector3, Vector4; a Color for a vec3 colour

mat3, mat4

Matrix3, Matrix4

sampler2D, samplerCube, sampler3D, sampler2DArray

Texture, CubeTexture, Data3DTexture, DataArrayTexture

arrays such as float u[4], vec3 u[8]

A JavaScript array of the matching type (a Float32Array for floats)

struct

A plain object with one property per member, uniform names written as uStruct.member in the GLSL

Two details cause most of the confusion. A Color is stored in the working colour space (linear sRGB by default), so a Color passed as a uniform already behaves as a linear value in the shader. A Texture loaded as a base colour must have texture.colorSpace = THREE.SRGBColorSpace; the GPU then decodes it to linear when you sample it. The full story is in Textures and Colour Management.

Example 1: a wobbling book cover

The example loads the Bookshelf cover texture, displaces a plane in the vertex shader with a travelling wave, and brightens the edges in the fragment shader. It is a complete main.js; the HTML is the one from the getting-started page with a canvas or a plain body. The texture file is bookshelf-cover.png and goes into the Vite public/ folder.

Storyboard of five panels: a plain quad, a ShaderMaterial, a time uniform, a sine displacement and an edge tint
Figure 2. Building the effect one idea at a time
import * as THREE from 'three';

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

const scene = new THREE.Scene();
scene.background = new THREE.Color(0x1b1b22);
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 50);
camera.position.set(0, 0, 4);

const cover = new THREE.TextureLoader().load('/bookshelf-cover.png');
cover.colorSpace = THREE.SRGBColorSpace; // sampled values arrive linear in the shader
cover.anisotropy = renderer.capabilities.getMaxAnisotropy();

const vertexShader = /* glsl */ `
  uniform float uTime;
  uniform float uAmplitude;
  varying vec2 vUv;
  void main() {
    vUv = uv;
    vec3 p = position;
    // a wave that travels along x and fades towards the spine on the left
    float fade = smoothstep(-0.5, 0.5, p.x);
    p.z += sin(p.x * 6.0 - uTime * 2.0) * uAmplitude * fade;
    gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
  }
`;

const fragmentShader = /* glsl */ `
  uniform sampler2D uMap;
  uniform vec3 uGlow;
  varying vec2 vUv;
  void main() {
    vec4 texel = texture2D(uMap, vUv);
    // distance to the nearest edge of the cover, 0 at the border and 0.5 in the middle
    vec2 d = min(vUv, 1.0 - vUv);
    float edge = 1.0 - smoothstep(0.0, 0.08, min(d.x, d.y));
    gl_FragColor = vec4(texel.rgb + uGlow * edge, texel.a);
    #include <tonemapping_fragment>
    #include <colorspace_fragment>
  }
`;

const material = new THREE.ShaderMaterial({
  uniforms: {
    uTime: { value: 0 },
    uAmplitude: { value: 0.12 },
    uMap: { value: cover },
    uGlow: { value: new THREE.Color(0xffc857) },
  },
  vertexShader,
  fragmentShader,
  side: THREE.DoubleSide,
});

// 64 x 64 segments: a vertex shader can only move vertices that exist
const mesh = new THREE.Mesh(new THREE.PlaneGeometry(1.6, 2.2, 64, 64), material);
scene.add(mesh);

const timer = new THREE.Timer();
timer.connect(document);

renderer.setAnimationLoop(() => {
  timer.update();
  material.uniforms.uTime.value = timer.getElapsed();
  renderer.render(scene, camera);
});

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

What the example shows, and why each line is there:

  • The wave is computed per vertex, so the plane needs many segments. The fragment shader cannot move geometry.

  • varying vec2 vUv carries the interpolated texture coordinates from the vertex to the fragment stage, exactly as in the raw WebGL pipeline of The WebGL Rendering Pipeline.

  • The two #include lines at the end are the part people forget. A ShaderMaterial writes whatever gl_FragColor holds to the output; the conversion from the linear working space to the sRGB display space, and the renderer’s tone mapping, are only applied when you include those chunks. Without colorspace_fragment the linear values reach the screen unconverted and the picture looks too dark and flat.

  • The timer is THREE.Timer, which replaces the deprecated Clock from r183; connect(document) pauses it when the tab is hidden.

  • uGlow is a Color, so it is already linear; adding it before the colour-space chunk keeps the arithmetic in linear space, which is where light additions belong.

GLSL ES 3.00 with glslVersion

With glslVersion: THREE.GLSL3 you may write modern syntax. The same fragment shader looks like this:

const fragmentShader3 = /* glsl */ `
  uniform sampler2D uMap;
  uniform vec3 uGlow;
  in vec2 vUv;
  void main() {
    vec4 texel = texture(uMap, vUv);
    vec2 d = min(vUv, 1.0 - vUv);
    float edge = 1.0 - smoothstep(0.0, 0.08, min(d.x, d.y));
    gl_FragColor = vec4(texel.rgb + uGlow * edge, texel.a);
    #include <colorspace_fragment>
  }
`;

const material3 = new THREE.ShaderMaterial({
  glslVersion: THREE.GLSL3,
  uniforms: material.uniforms,
  vertexShader: vertexShader.replace('varying vec2 vUv;', 'out vec2 vUv;'),
  fragmentShader: fragmentShader3,
});

The differences from the legacy syntax are the ones documented in GLSL ES 1.00 and 3.00: in/out instead of attribute/varying, texture() instead of texture2D(), and a user-declared fragment output with layout(location = n) out for multiple render targets. For a ShaderMaterial, three.js defines the output so that gl_FragColor keeps working; a RawShaderMaterial must declare its own output variable and begin with #version 300 es. Two uniforms objects can be shared between materials (as above) when you want one slider to drive both, but then UniformsUtils.clone is the way to give each material its own copy.

Writing a RawShaderMaterial

A RawShaderMaterial is the same API with an empty prefix. Everything the shader touches must be declared, and precision must be set in the fragment shader:

const raw = new THREE.RawShaderMaterial({
  glslVersion: THREE.GLSL3,
  uniforms: { uColor: { value: new THREE.Color(0x4f46e5) } },
  vertexShader: /* glsl */ `#version 300 es
    uniform mat4 modelViewMatrix;
    uniform mat4 projectionMatrix;
    in vec3 position;
    void main() {
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }`,
  fragmentShader: /* glsl */ `#version 300 es
    precision mediump float;
    uniform vec3 uColor;
    out vec4 outColor;
    void main() { outColor = vec4(uColor, 1.0); }`,
});

The renderer still fills modelViewMatrix and projectionMatrix because it recognises the declared names; what it does not do is add the declarations, the #include expansion or the colour-space handling. It also does not add the #version line, so the text above carries it. Use this class when you want to know exactly what the driver receives.

Patching a built-in material with onBeforeCompile

A built-in material is a template: its GLSL is a list of #include <name> lines, and each name is a chunk stored in THREE.ShaderChunk. The renderer expands the chunks, then calls the material’s onBeforeCompile(shader, renderer) once, before compiling the program. The shader object holds vertexShader and fragmentShader (the template text, with the #include lines still visible) and uniforms. You edit the strings and add uniforms; the edited version is what gets compiled.

Diagram: ShaderLib source with include lines, resolved through the ShaderChunk table, linked into the final GLSL, with onBeforeCompile editing the text in between
Figure 3. The path from a built-in shader to the program that is compiled, with the patch point

Example 2: the shelf sways in the wind

The shelf from bookshelf.glb uses MeshStandardMaterial. The patch below moves the vertices of every material in the loaded scene by a sine wave scaled by height, while lights, shadows and the PBR look are untouched.

import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const uTime = { value: 0 }; // one uniform object shared by every patched material

function addSway(material) {
  material.onBeforeCompile = (shader) => {
    shader.uniforms.uTime = uTime;
    shader.uniforms.uStrength = { value: 0.03 };

    shader.vertexShader = shader.vertexShader
      .replace(
        '#include <common>',
        `#include <common>
         uniform float uTime;
         uniform float uStrength;`
      )
      .replace(
        '#include <begin_vertex>',
        `#include <begin_vertex>
         // transformed is the object-space position after the begin_vertex chunk
         transformed.x += sin(uTime * 1.5 + transformed.y * 3.0) * uStrength * transformed.y;`
      );
  };
  // materials with and without the patch must not share a compiled program
  material.customProgramCacheKey = () => 'sway-v1';
  material.needsUpdate = true;
}

const gltf = await new GLTFLoader().loadAsync('/bookshelf.glb');
gltf.scene.traverse((o) => {
  if (!o.isMesh) return;
  const materials = Array.isArray(o.material) ? o.material : [o.material];
  materials.forEach(addSway);
});
scene.add(gltf.scene);

renderer.setAnimationLoop((ms) => {
  uTime.value = ms / 1000;
  renderer.render(scene, camera);
});

Things to know about this technique:

  • Match the text exactly. String.replace with a string that is not found silently does nothing. #include <begin_vertex> and #include <common> are stable anchors, but the chunk contents change between releases. After upgrading three.js, print shader.vertexShader once (or read the chunk with THREE.ShaderChunk.begin_vertex) and check that your patch still lands where you expect.

  • Shadows need the same patch. The shadow pass uses a separate depth material, so a displaced mesh casts its un-displaced shadow. Assign a patched customDepthMaterial (a MeshDepthMaterial carrying the same edit) to the mesh, and customDistanceMaterial for point lights.

  • Program caching. Materials that are the same class and have the same parameters share one compiled program. When the patch text differs between materials, give each variant its own customProgramCacheKey; when the patch is identical the key lets them share.

  • Uniforms are shared by object. Assigning shader.uniforms.uTime = uTime keeps one { value } for all materials so a single assignment per frame updates every one.

  • needsUpdate. Set it after assigning onBeforeCompile to a material that has already been rendered, so the program is rebuilt.

  • Not for WebGPURenderer. onBeforeCompile is ignored there; the equivalent is a node graph, see the last section.

Other injection points

Chunk What it controls Typical edit

begin_vertex

Declares vec3 transformed = vec3( position );

Displace vertices: wind, waves, explosions.

project_vertex

Applies model-view and projection to transformed

Replace the projection (billboards, curved world).

beginnormal_vertex, defaultnormal_vertex

The object-space normal and its transform

Keep normals correct after displacement.

map_fragment

Multiplies the diffuse colour by the map

Tint, recolour or dissolve the base colour.

color_fragment, alphamap_fragment

Vertex colours and the alpha map

Alpha cutouts and dissolve edges.

emissivemap_fragment

Adds the emissive map

Pulsing emissive light (feeds bloom).

opaque_fragment, tonemapping_fragment, colorspace_fragment

Writes the final colour, applies tone mapping and the output colour space

Debug views; anything after them overwrites the lit result.

Keeping shaders in their own files

Embedding GLSL in template strings is fine for a few lines. For longer shaders, Vite imports any file as text with the ?raw suffix, which also gives you syntax highlighting in the editor:

import vertexShader from './shaders/wobble.vert?raw';
import fragmentShader from './shaders/wobble.frag?raw';

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

Reusable snippets can be shared between shaders with your own #include support: ShaderMaterial resolves #include <name> only for names registered in THREE.ShaderChunk, so a project chunk is added with THREE.ShaderChunk.myNoise = noiseSource before the first render and then included as #include <myNoise>.

Debugging shader errors

  • The console message. On a compile or link error three.js logs the driver’s message together with the source, with line numbers that include the prefix it added, so the line in your text is offset. renderer.debug.checkShaderErrors (true by default) controls this; switching it off in production saves a synchronous getProgramParameter call per program.

  • A custom handler. Assign renderer.debug.onShaderError = (gl, program, vertexShader, fragmentShader) => { ... } to show the log in your own UI.

  • Visual debugging. Write intermediate values to the colour: gl_FragColor = vec4( vUv, 0.0, 1.0 ) shows the UVs, vec4( normal * 0.5 + 0.5, 1.0 ) shows normals. Remember that the colour-space chunk changes what you see; leave it out while debugging raw values.

  • Tools. Spector.js and the browser devtools show the final program text and uniform values, as described in Performance and Debugging.

Pitfalls

  • Washed-out or too dark colours. Missing #include <colorspace_fragment> in a ShaderMaterial, or a texture without colorSpace = SRGBColorSpace.

  • Everything invisible. gl_Position computed without the projection, the mesh culled because of side, or alpha below 1 without transparent: true (the sort order then puts it behind the background).

  • A moved vertex but the old shadow or the old picking. The depth and raycast code use the original geometry; a Raycaster intersects the un-displaced mesh.

  • Uniform not updating. The uniform name in the JavaScript object differs from the GLSL name, or the object was replaced (material.uniforms = { ... } after the first render) instead of editing .value.

  • Instances all at one place. A custom vertex shader on an InstancedMesh must apply instanceMatrix; either include the chunks or multiply by it yourself.

  • Shared vectors. Putting one Vector3 object in two materials links them; clone it.

  • Allocations in the loop. new THREE.Color() or new THREE.Vector3() each frame creates garbage that causes stutters; update the existing value with .set() and .copy().

Performance notes

Uniform updates are cheap. Compiling is not: each distinct combination of material class, defines and patch text is one program, and a compile can take tens of milliseconds, in a stall that shows up as a dropped frame. Keep the number of variants small, change defines rarely, and use renderer.compileAsync(scene, camera) (with KHR_parallel_shader_compile where available) to compile before the first frame, as described in Performance and Disposal. Vertex displacement is free compared with the fragment cost of procedural noise: a 5-octave noise per pixel at a high device pixel ratio is the usual cause of a slow custom shader, so cap the ratio as the examples do.

Custom shaders and WebGPURenderer

WebGPURenderer (imported from three/webgpu) generates WGSL, or GLSL for its WebGL 2 fallback, from node graphs written in TSL. ShaderMaterial, RawShaderMaterial and onBeforeCompile are not supported there, and EffectComposer is not either. A GLSL shader must therefore be rewritten as a node material (MeshStandardNodeMaterial, NodeMaterial) if the project is to move; the wobbling cover above becomes about ten lines of positionLocal, time and sin() nodes. The migration and the TSL basics are in WebGPURenderer and TSL. Until then, projects that depend on custom GLSL stay on WebGLRenderer, which remains fully supported.

Where the books are outdated

The books cover custom shaders in PAR chapter 3, LTJ chapter 4 (and 11 for shader-based post-processing) and TCB chapter 5.

Book idea Today

Shaders stored in <script type="x-shader/x-vertex"> elements and read with getElementById

Template strings, or separate files imported with ?raw through Vite. The script-tag approach still works but is not how a bundled project is organised.

A global THREE object and scripts from examples/js

ES modules from three and three/addons/; the examples/js folder was removed in r148.

GLSL ES 1.00 only, gl_FragColor, texture2D

WebGLRenderer has required WebGL 2 since r163; glslVersion: THREE.GLSL3 allows GLSL ES 3.00 syntax. Legacy syntax keeps compiling for a ShaderMaterial.

ShaderMaterial options such as attributes, derivatives flags

Attributes are taken from the geometry; derivatives are core in WebGL 2. Check the current parameter table above.

Colour output as raw gl_FragColor, with gammaInput and gammaOutput

Colour management is on by default (r152); a ShaderMaterial converts only if it includes colorspace_fragment.

Patching shaders by copying the whole ShaderLib source

onBeforeCompile with ShaderChunk anchors, available as a stable hook since long before r187.

Custom shaders as the way to reach every effect

Still valid for WebGLRenderer; for WebGPURenderer use TSL.

References