First Shader
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_FragColoralpha withvUv.xfor a gradient fade
ShaderMaterial로 GLSL로 커스텀 GPU 코드를 작성할 수 있습니다. 프레임마다 두 프로그램이 실행됩니다: 버텍스 셰이더(버텍스 이동)와 프래그먼트 셰이더(픽셀 색상).
ShaderMaterial 설정
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);
}
`,
});
유니폼 업데이트
// animate() 내부:
material.uniforms.uTime.value = clock.getElapsedTime();
실험해보기
- 마우스 위치를 유니폼으로 전달:
{ value: new THREE.Vector2() } mix(colorA, colorB, vUv.y)로 수직 그래디언트gl_FragColor알파를vUv.x로 설정해 그래디언트 페이드