Shader guide

Three.js ShaderMaterial Example

ShaderMaterial is useful when MeshStandardMaterial cannot express the color, distortion, mask, or animated surface you want.

Best starter: A plane geometry, UV coordinates, a uTime uniform, and one color uniform. Add complexity after the first pattern renders.

Small ShaderMaterial setup

const uniforms = {
  uTime: { value: 0 },
  uColorA: { value: new THREE.Color("#2f8f83") },
  uColorB: { value: new THREE.Color("#151b24") }
};

const material = new THREE.ShaderMaterial({
  uniforms,
  vertexShader: `
    varying vec2 vUv;

    void main() {
      vUv = uv;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
    }
  `,
  fragmentShader: `
    uniform float uTime;
    uniform vec3 uColorA;
    uniform vec3 uColorB;
    varying vec2 vUv;

    void main() {
      float wave = 0.5 + 0.5 * sin(vUv.x * 12.0 + uTime);
      vec3 color = mix(uColorA, uColorB, wave);
      gl_FragColor = vec4(color, 1.0);
    }
  `
});

function animate(time) {
  uniforms.uTime.value = time * 0.001;
  renderer.render(scene, camera);
}

Debug the first blank screen

  • Confirm the material compiles by replacing the fragment shader with a solid color.
  • Check that the geometry has UV coordinates before using vUv.
  • Keep uniforms as objects with a value property, then update that value in the animation loop.
  • Open DevTools and read the WebGL shader compiler error. It usually points to the line that failed.

When to use ShaderMaterial

Animated surfaces

Use uTime for waves, scanning lines, pulses, soft masks, and other effects tied to frame time.

Procedural color

Use UVs, normals, or world position to mix colors without loading texture files.

Particles

Use a shader when each point needs a custom size, alpha, or color rule based on position or time.

Learning GLSL

A full-screen plane is the calmest place to learn coordinates, color mixing, and uniforms.

FAQ

What is a uniform in Three.js?

A uniform is a value passed from JavaScript into the shader program. It is shared across the rendered object for that draw call.

Do I need RawShaderMaterial?

Most starter scenes should use ShaderMaterial. RawShaderMaterial gives more control, but you must provide more GLSL plumbing yourself.

Can ShaderMaterial work on imported GLB models?

Yes, but begin with a plane or sphere. Once the shader works, apply it to selected meshes from the loaded GLB scene.

Related Three.js Lab pages

Sources