First Shader

Lesson 9

ShaderMaterial lets you write custom GPU code in GLSL. Two programs run per frame: the vertex shader (moves vertices) and the fragment shader (colors pixels).

ShaderMaterial Setup

const material = new THREE.ShaderMaterial({
  uniforms: {
    uTime:  { value: 0 },
    uColor: { value: new THREE.Color(0x00aaff) },
  },
  vertexShader: `
    uniform float uTime;
    varying vec2 vUv;
    void main() {
      vUv = uv;
      vec3 pos = position;
      pos.z += sin(pos.x * 3.0 + uTime) * 0.1;
      gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
    }
  `,
  fragmentShader: `
    uniform vec3 uColor;
    uniform float uTime;
    varying vec2 vUv;
    void main() {
      vec3 col = uColor;
      col += sin(vUv.x * 10.0 + uTime) * 0.2;
      gl_FragColor = vec4(col, 1.0);
    }
  `,
});

Updating Uniforms

// In animate():
material.uniforms.uTime.value = clock.getElapsedTime();

What to Experiment With

  • Pass mouse position as a uniform: { value: new THREE.Vector2() }
  • Use mix(colorA, colorB, vUv.y) for a vertical gradient
  • Replace gl_FragColor alpha with vUv.x for a gradient fade