Three.js Materials
Targets three.js r186. Examples use WebGLRenderer; the WebGPU and TSL section uses WebGPURenderer.
Quick Start
import * as THREE from "three";
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 0, 3);
// PBR material - the default choice for lit, realistic surfaces
const material = new THREE.MeshStandardMaterial({
color: 0x00aaff,
roughness: 0.35,
metalness: 0.1,
});
const mesh = new THREE.Mesh(new THREE.SphereGeometry(1, 48, 32), material);
scene.add(mesh);
scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1)); // lit materials render black without lights
const light = new THREE.DirectionalLight(0xffffff, 2);
light.position.set(3, 3, 3);
scene.add(light);
function animate() {
mesh.rotation.y += 0.01;
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);Material Types Overview
| Material | Use case | Lighting |
|---|---|---|
| MeshBasicMaterial | Unlit color, textures, wireframes | None |
| MeshLambertMaterial | Matte diffuse surfaces | Diffuse |
| MeshPhongMaterial | Shiny plastic, cheap specular | Diffuse + specular |
| MeshStandardMaterial | PBR metal/rough workflow | PBR |
| MeshPhysicalMaterial | PBR plus clearcoat, transmission, sheen, iridescence | PBR |
| MeshToonMaterial | Cel shading | Toon steps |
Color data textures (map, emissiveMap, specularMap, sheenColorMap, specularColorMap, LDR matcap, a canvas or video used as color) need texture.colorSpace = THREE.SRGBColorSpace, or colors render washed out. Scalar maps (normal, bump, displacement, roughness, metalness, ao, alpha, toon gradientMap) keep the default. HDR loaders set their own color space.
MeshBasicMaterial
No lighting calculations. Fast, always visible. Supports envMap with reflectivity (0 to 1) and combine (THREE.MultiplyOperation, THREE.MixOperation, THREE.AddOperation); specularMap (sRGB) masks the env-map contribution.
const map = await new THREE.TextureLoader().loadAsync("color.jpg");
map.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.MeshBasicMaterial({
color: 0xffffff, // multiplied with the map
map,
MeshLambertMaterial and MeshPhongMaterial
Lambert is diffuse-only. Phong adds a specular highlight; it is the cheap alternative when Standard is too heavy.
const lambert = new THREE.MeshLambertMaterial({
color: 0x00ff00,
emissive: 0x111111, // self-illumination color
emissiveIntensity: 1,
});
const phong = new THREE.MeshPhongMaterial({
color: 0x0000ff
Both also support map, emissiveMap, specularMap (sRGB; masks the env-map reflection, and the highlight on Phong), normalMap, bumpMap, displacementMap, aoMap, envMap, envMapIntensity and envMapRotation.
MeshStandardMaterial (PBR)
Physically-based rendering. Recommended for realistic results.
const map = await new THREE.TextureLoader().loadAsync("color.jpg");
map.colorSpace = THREE.SRGBColorSpace;
const ormMap = await new THREE
lightMap (with lightMapIntensity) bakes indirect light the same way aoMap bakes occlusion; an HDR or EXR lightMap is LinearSRGBColorSpace, which the loaders set.
UV channels: aoMap and lightMap read the channel you pick
Every UV-mapped texture samples the attribute selected by texture.channel: 0 reads uv (the default), 1 reads uv1, 2 reads uv2, 3 reads uv3. aoMap and lightMap need no second UV set - they sample uv unless you change channel. GLTFLoader loads TEXCOORD_1 as uv1 and sets channel itself.
const aoMap = await new THREE.TextureLoader().loadAsync("ao.jpg"); // scalar: keep default
const material = new THREE.MeshStandardMaterial({ aoMap }); // samples uv: no extra attribute needed
// Alternative for a separate unwrap (a baked AO or light map): copy your baker's u,v pairs into uv1
const bakedUv
MeshPhysicalMaterial (Advanced PBR)
Extends MeshStandardMaterial with layer and volume features. Texture variants exist for most of them: clearcoatMap, clearcoatRoughnessMap, clearcoatNormalMap, transmissionMap, thicknessMap, iridescenceMap, iridescenceThicknessMap, sheenColorMap, sheenRoughnessMap, anisotropyMap, specularIntensityMap, specularColorMap.
const material = new THREE.MeshPhysicalMaterial({
// Clearcoat (car paint, lacquer)
clearcoat: 1.0, // 0 = none, 1 = full coat
clearcoatRoughness: 0.1,
// Transmission (glass, water) - refracts the opaque objects and scene.background behind it
transmission:
Glass - transmission with a smooth surface and something behind it to refract:
const glass = new THREE.MeshPhysicalMaterial({
color: 0xffffff,
metalness: 0,
roughness: 0,
transmission: 1,
thickness: 0.5,
ior: 1.5,
});
// transmission refracts the opaque objects and background behind it; scene.environment adds its reflectionsMeshToonMaterial
Cel shading. The gradient map is non-color data - keep its default color space.
const steps = new Uint8Array([120, 200]); // two shading steps
const gradientMap = new THREE.DataTexture(steps, 2, 1, THREE.RedFormat);
gradientMap.minFilter = THREE.NearestFilter; // hard steps; LinearFilter blends them
MeshNormalMaterial and MeshDepthMaterial
// Normals encoded as RGB - debugging and flat illustrative looks
const normals = new THREE.MeshNormalMaterial({ flatShading: false, wireframe: false });
// Depth as grayscale (BasicDepthPacking, the default); RGBADepthPacking packs it for reading back in a shader
const depth = new THREE.MeshDepthMaterial();PointsMaterial
For point clouds. size is in pixels; with sizeAttenuation (the default, perspective cameras only) it is multiplied by half the canvas height and divided by the point's view-space depth.
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute([0, 0, 0, 1, 0.5, 0, 0.5,
LineBasicMaterial and LineDashedMaterial
WebGL and WebGPU always draw line primitives 1 px wide; linewidth, linecap and linejoin only affect the SVGRenderer. For thick lines under WebGLRenderer use Line2 with LineGeometry and LineMaterial from three/addons/lines/ (linewidth in pixels); LineMaterial is a ShaderMaterial, so WebGPURenderer needs Line2 from three/addons/lines/webgpu/Line2.js, which uses Line2NodeMaterial.
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute([-1, 0, 0, 1, 0, 0],
ShaderMaterial (WebGLRenderer only)
Custom GLSL with three.js uniforms injected for you. It always compiles as GLSL ES 3.00: texture(), textureLod() and dFdx work, and texture2D / gl_FragColor remain as aliases - leave glslVersion unset. ShaderMaterial, RawShaderMaterial and onBeforeCompile have no WebGPURenderer path; there, use node materials and TSL.
const timer = new THREE.Timer();
timer.connect(document); // pause when the tab is hidden
const material = new THREE.ShaderMaterial({
uniforms: { time: { value: 0 } },
vertexShader:
Declared for you in the shader: modelMatrix, modelViewMatrix, projectionMatrix, viewMatrix, normalMatrix, cameraPosition, and the attributes position, normal, uv (plus instanceMatrix on an InstancedMesh, which you apply yourself: projectionMatrix * modelViewMatrix * instanceMatrix * vec4(pos, 1.0), and color with vertexColors). The extra uv sets and tangent are not declared - add in vec2 uv1; yourself.
RawShaderMaterial (WebGLRenderer only)
No declarations are prepended (only #version from glslVersion, the SHADER_TYPE and SHADER_NAME defines, and your defines), but the renderer still sets projectionMatrix, modelViewMatrix, viewMatrix, normalMatrix, modelMatrix and cameraPosition - declare them in the shader and never pass them in uniforms: a same-named entry is overwritten every draw (modelMatrix, modelViewMatrix, normalMatrix) or replaces the camera's value (projectionMatrix, viewMatrix, cameraPosition).
const material = new THREE.RawShaderMaterial({
glslVersion: THREE.GLSL3, // without it the shader is GLSL ES 1.00, which has no texture()
vertexShader: `
precision highp float;
in vec3 position;
uniform mat4 projectionMatrix;
uniform mat4 modelViewMatrix;
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
Common Properties
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
material.visible = true;
material.transparent = false; // true for opacity below 1; toggling it after the first render needs needsUpdate
material.opacity = 1.0;
// Multiply and subtractive blending require premultiplied alpha (both renderers)
const material = new THREE.MeshBasicMaterial({ color: 0x8844ff });
material.blending = THREE.SubtractiveBlending; // same for THREE.MultiplyBlending
material.premultipliedAlpha = true
Multiple Materials per Mesh
// One material per geometry group; BoxGeometry has six, in the order +x, -x, +y, -y, +z, -z
const geometry = new THREE.BoxGeometry(1, 1, 1);
const colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff
Environment Maps
An equirectangular HDR file lights and reflects every PBR material in the scene. Both renderers prefilter it themselves - no PMREM step needed.
import { HDRLoader } from "three/addons/loaders/HDRLoader.js";
const env = await new HDRLoader().loadAsync("environment.hdr");
env.mapping = THREE.EquirectangularReflectionMapping; // without it a background draws as a flat quad
scene.environment = env; // lights and reflects PBR materials
scene.background = env;
const cubeEnv = new THREE.CubeTextureLoader().load([
"px.jpg", "nx.jpg", "py.jpg", "ny.jpg", "pz.jpg", "nz.jpg",
]);
const material = new THREE.MeshStandardMaterial({ envMap: cubeEnv });
scene.environment lights MeshStandardMaterial and MeshPhysicalMaterial on both renderers. With WebGLRenderer it also lights MeshLambertMaterial and MeshPhongMaterial; WebGPURenderer does not.
Runtime Changes, Cloning, Disposal
mesh.material.color.set(0xff0000); // uniform values: no recompile needed
mesh.material.roughness = 0.8;
// material.needsUpdate = true after changing a setting compiled into the shader:
// transparent, side, blending, flatShading, vertexColors, dithering, premultipliedAlpha, alphaHash,
// adding or removing a map slot, or shader source (alphaTest and envMap recompile by themselves)
const clone = mesh.material.clone(); // copies values; map slots share their textures, ShaderMaterial uniforms are clonedDispose a material nothing else uses: material.dispose() releases its GPU programs, which are deleted once no other material uses them; textures need their own texture.dispose().
Performance, in order of impact:
- Share one material instance across meshes - the renderer re-uploads material uniforms whenever consecutive draws switch material (identical settings already share one compiled program).
- Prefer opaque rendering: transparent materials are sorted back to front by object and drawn after the opaque ones, still writing depth unless
depthWrite: false, so stacked layers overdraw and intersecting ones misorder; for cutouts, alphaTest keeps the material opaque, so it draws in the opaque pass, correctly in any order. - Pick the cheapest material that looks right: Basic, then Lambert, Phong, Standard, Physical.
WebGPU and TSL
MeshStandardMaterial and the other built-in classes run under WebGPURenderer unchanged - the renderer converts them to node materials automatically; ShaderMaterial, RawShaderMaterial, MeshDepthMaterial and MeshDistanceMaterial have no node equivalent and log Material "..." is not compatible. For custom shading use the node material classes from three/webgpu with TSL nodes from three/tsl; they target WebGPURenderer, and WebGLRenderer draws them only through the WebGLNodesHandler addon (three/addons/tsl/WebGLNodesHandler.js, passed to renderer.setNodesHandler()), a migration aid without VSM shadows, MRT, transmission or the WebGPU post-processing stack.
import * as THREE from "three/webgpu";
const renderer = new THREE.WebGPURenderer({ antialias: true });
await renderer.init(); // before any other use of the renderer
renderer.setPixelRatio(window.devicePixelRatio);
import * as THREE from "three/webgpu";
import { texture, mix, color, float, time, positionLocal, normalLocal, sin } from "three/tsl";
// Unlit: the node equivalent of a color ShaderMaterial
const unlit = new THREE.MeshBasicNodeMaterial();
unlit.colorNode
import * as THREE from "three/webgpu";
import { instancedBufferAttribute } from "three/tsl";
// The WebGPU backend draws Points at 1 px whatever the size; draw larger points as quads
const positions = new THREE.InstancedBufferAttribute(new Float32Array(1500),
Common Mistakes
geometry.setAttribute("uv2", geometry.attributes.uv)→const material = new THREE.MeshStandardMaterial({ aoMap });: aoMap samples the attribute picked byaoMap.channel, 0 (uv) by default, so it needs no extra attribute and uv2 is read only withaoMap.channel = 2; only a separate unwrap goes inuv1withaoMap.channel = 1.new RGBELoader()→new HDRLoader(): HDRLoader was renamed from RGBELoader in r180; RGBELoader is deprecated and still loads, with a warning - import HDRLoader from "three/addons/loaders/HDRLoader.js"."three/examples/jsm/loaders/HDRLoader.js"→"three/addons/loaders/HDRLoader.js": the browser import maps mapthree/addons/to examples/jsm/ and define nothree/examples/key, so the examples path fails there.material.blending = THREE.MultiplyBlending;→material.blending = THREE.MultiplyBlending; material.premultipliedAlpha = true;: multiply and subtractive blending require premultiplied alpha, or the renderer logs an error and sets no blend function.
See Also
threejs-textures- loading, color spaces, filters and channels in depththreejs-shaders- GLSL authoring, shader chunks and debugging under WebGLRendererthreejs-lighting- lights, shadows and how they interact with materials