首页 / three.js / API 文档
ShaderMaterial
先看结论
自定义着色器材质。顶点与片元代码完全由自己编写, three.js 只负责编译、绑定与传入内置矩阵。
new THREE.ShaderMaterial(parameters)
构造参数
| 参数 | 默认 | 说明 |
|---|---|---|
uniforms | {} | 着色器变量,值为 { value } 形式 |
vertexShader | '' | 顶点着色器源码 |
fragmentShader | '' | 片元着色器源码 |
defines | {} | 编译期宏定义,修改后需要重新编译 |
glslVersion | null | 设为 THREE.GLSL3 使用 GLSL ES 3.0 语法 |
lights | false | 是否注入 three.js 的光照计算代码 |
clipping | false | 是否支持裁剪平面 |
fog | false | 是否支持场景雾 |
wireframe | false | 线框模式 |
transparent / opacity | false / 1 | 透明度 |
side | FrontSide | 面朝向与双面渲染 |
depthTest / depthWrite | true / true | 深度测试与写入 |
属性与方法
| 成员 | 说明 |
|---|---|
uniforms | 变量对象,改 .value 即可生效 |
uniformsNeedUpdate | true 时强制重新上传 uniforms |
defines | 宏定义 |
extensions | 着色器扩展开关,如 { derivatives: true } |
defaultAttributeValues | 几何缺少属性时使用的默认值 |
index0AttributeName | 指定索引为 0 的顶点属性名 |
setValues(parameters) | 批量设置构造参数 |
clone() / copy(source) | 复制,uniforms 会被深拷贝 |
示例
const uniforms = {
uTime: { value: 0 },
uColor: { value: new THREE.Color('#4aa3df') },
uAmplitude: { value: 1.4 }
};
const material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: `
uniform float uTime;
uniform float uAmplitude;
varying float vHeight;
void main() {
vec3 p = position;
float h = sin(p.x * 0.8 + uTime) * cos(p.z * 0.8 + uTime) * uAmplitude;
p.y += h;
vHeight = h;
gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
}
`,
fragmentShader: `
uniform vec3 uColor;
varying float vHeight;
void main() {
vec3 c = mix(uColor, vec3(1.0), clamp(vHeight * 0.4 + 0.4, 0.0, 1.0));
gl_FragColor = vec4(c, 1.0);
}
`,
side: THREE.DoubleSide
});
function animate(t) {
uniforms.uTime.value = t * 0.001;
renderer.render(scene, camera);
}
可直接使用的内置变量
| 名称 | 说明 |
|---|---|
position | 顶点属性,来自几何体 |
normal | 法线属性,几何体没有时不定义 |
uv | UV 属性 |
modelMatrix | 模型矩阵 |
viewMatrix | 视图矩阵 |
modelViewMatrix | 模型视图矩阵 |
projectionMatrix | 投影矩阵 |
normalMatrix | 法线矩阵 |
GLSL3 与旧语法
glslVersion: THREE.GLSL3 时必须用 in、out
代替 attribute、varying,片元输出用自定义
out vec4,且不能再用 gl_FragColor。
混用两套语法会在编译期报错,错误信息只出现在控制台,
页面上表现为物体消失。
共享 uniforms 要小心。多个材质引用同一个 uniforms 对象时,
改一个值会同时影响所有材质。需要独立控制时先
THREE.UniformsUtils.clone(uniforms) 再交给材质。
经纬志(2026)。《ShaderMaterial》。https://www.jingweizhi.com/three/api/shader-material.html(访问日期 2026-11-03)。