Three.js Textures
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(60, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 0, 2);
// Color images must be tagged sRGB or they render too bright and washed out
const texture = new THREE.TextureLoader().load("diffuse.jpg");
texture.colorSpace = THREE.SRGBColorSpace;
const mesh = new THREE.Mesh(
new THREE.PlaneGeometry(2, 2),
new THREE.MeshBasicMaterial({ map: texture }),
);
scene.add(mesh);
renderer.setAnimationLoop(animate);
function animate() {
mesh.rotation.z += 0.01;
renderer.render(scene, camera);
}Loading
// load() returns the texture at once; its image arrives asynchronously
const texture = new THREE.TextureLoader().load("diffuse.jpg");
texture.colorSpace = THREE.SRGBColorSpace;
mesh.material.map = texture; // before the first render; afterwards also set mesh.material.needsUpdate = true
// When the next step needs the loaded image, await it
const colorMap = await
TextureLoader's onProgress parameter is unsupported and never fires; a LoadingManager reports progress as each file finishes:
const manager = new THREE.LoadingManager();
manager.onProgress = (url, loaded, total) => console.log(`${loaded}/${total}: ${url}`);
const loader = new THREEColor Space
Color management is on by default and every texture starts at NoColorSpace:
- LDR color images get
SRGBColorSpace:map,emissiveMap,specularMap, sheen color and specular color maps, LDR matcaps, and canvas or video used as color. - Scalar data keeps
NoColorSpace: normal, bump, displacement, roughness, metalness, ambient-occlusion and alpha maps. - HDR environments are
LinearSRGBColorSpace; the HDR loaders set that themselves. GLTFLoader sets the color spaces of the textures it loads.
const colorMap = new THREE.TextureLoader().load("color.jpg");
colorMap.colorSpace = THREE.SRGBColorSpace; // authored color image
const normalMap = new THREE.TextureLoader().load("normal.jpg");
// normalMap stays at NoColorSpace: it is data, not colorTransform: Wrap, Repeat, Offset, Rotation
const texture = new THREE.TextureLoader().load("diffuse.jpg");
// Tiling requires repeat wrapping; the default clamps edge pixels
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(4, 4); // tile 4x4
MirroredRepeatWrapping tiles with a mirror flip on each repeat.
Filtering, Mipmaps, Anisotropy
const texture = new THREE.TextureLoader().load("diffuse.jpg");
// Minification (many texture pixels per screen pixel)
texture.minFilter = THREE.LinearMipmapLinearFilter; // default: trilinear blend between mip levels
texture.minFilter = THREE.NearestFilter;
Texture Types
Base class from any image element:
const image = new Image();
image.src = "sprite.png";
const imageTexture = new THREE.Texture(image);
imageTexture.colorSpace = THREE.SRGBColorSpace;
image.onload = () => (imageTexture.needsUpdate = true); // upload once the pixels existDataTexture from raw typed-array pixels. Its defaults differ from Texture: NearestFilter for both filters, flipY false, mipmaps off:
const size = 256;
const data = new Uint8Array(size * size * 4); // RGBA, one byte per channel
for (let i = 0; i < size; i++) {
for (let
CanvasTexture for dynamically drawn textures (sets needsUpdate on construction):
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#404040";
ctx.
VideoTexture for a playing HTMLVideoElement (re-uploads every frame, mipmaps off):
const video = document.createElement("video");
video.src = "video.mp4";
video.loop = true;
video.muted = true;
video.play();
const videoTexture = new THREE.VideoTexture(video);
VideoFrameTexture for WebCodecs: each decoded frame is pushed by hand:
const frameTexture = new THREE.VideoFrameTexture();
frameTexture.colorSpace = THREE.SRGBColorSpace;
const decoder = new VideoDecoder({
output(frame) {
if (frameTexture.image instanceof VideoFrame) frameTexture.image.close(); // free the replaced frame, or decoding stalls
HTMLTexture draws an HTML element through the browser's HTML-in-Canvas API: the renderer moves the element into its own canvas and re-uploads it on paint events; where the browser lacks that API the texture stays empty.
Compressed Textures (KTX2)
import { KTX2Loader } from "three/addons/loaders/KTX2Loader.js";
const ktx2Loader = new KTX2Loader();
// No setTranscoderPath call: the transcoder loads from the three package.
// Set one only when self-hosting the decoders, pinned to this release.
ktx2Loader.detectSupport(renderer); // required before loading; works with both renderers
const compressedMap = await ktx2Loader.loadAsync(
Basis Universal KTX2 transcodes to a compressed format the GPU supports: smaller uploads and less memory than PNG or JPEG, which upload uncompressed (where the GPU supports none of the targets, KTX2Loader also falls back to uncompressed RGBA). Compressed textures cannot be flipped or mipmapped at upload: flipY stays false, so author the file in the orientation your UVs expect, and mipmaps must be embedded in the file.
Environment Maps
Cube maps (the loader tags the result sRGB itself):
const cubeTexture = new THREE.CubeTextureLoader().load([
"px.jpg", "nx.jpg", // +X, -X
"py.jpg", "ny.jpg", // +Y, -Y
"pz.jpg", "nz.jpg", // +Z, -Z
]);
scene.background = cubeTexture;
scene.environment HDR equirectangular files — set mapping, then assign; both renderers prefilter the environment themselves:
import { HDRLoader } from "three/addons/loaders/HDRLoader.js";
const env = await new HDRLoader().loadAsync("environment.hdr");
env.mapping = THREE.EquirectangularReflectionMapping; // without it the background draws as a flat screen quad
scene.environment = env;
scene.background = env;EXRLoader (three/addons/loaders/EXRLoader.js) loads .exr files the same way and UltraHDRLoader loads Ultra HDR JPEGs; both set their own linear color space.
Scene-level controls:
scene.environmentIntensity = 0.5; // dim the image-based lighting
scene.environmentRotation.y = Math.PI / 4;
scene.backgroundBlurriness = 0.5; // 0-1
scene.backgroundIntensity = 1.0;
scene.backgroundRotation.y = Math.PI;Both renderers convert an equirectangular environment into a cube map with a larger texture internally (better sampling, more memory); when memory matters, ship a lower-resolution equirect file.
PMREMGenerator is for generated environments — a scene such as RoomEnvironment captured with fromScene:
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
const pmrem = new THREE.PMREMGenerator(renderer);
const room = new RoomEnvironment();
scene.environment = pmrem.fromScene(room, 0.04).texture;
room.dispose(); // frees the room's geometries and materials
Do not run a loaded equirect file through PMREMGenerator "for better reflections" — direct assignment with mapping set produces the same prefiltering.
Render Targets
const renderTarget = new THREE.WebGLRenderTarget(512, 512);
const rtScene = new THREE.Scene(); // must not contain the mesh that samples the target
rtScene.add(new THREE.Mesh(new
Depth buffer as a texture:
const depthTarget = new THREE.WebGLRenderTarget(512, 512);
depthTarget.depthTexture = new THREE.DepthTexture(512, 512); // default type UnsignedIntTypeMSAA and multiple attachments:
// MSAA: resolved into .texture automatically after rendering
const msaaTarget = new THREE.WebGLRenderTarget(512, 512, { samples: 4 });
// MRT: N color attachments, read back through .textures
const mrtTarget = new THREE.WebGLRenderTarget(512, 512, { count: 2 });
Dynamic Reflections
const cubeRenderTarget = new THREE.WebGLCubeRenderTarget(256, {
generateMipmaps: true,
minFilter: THREE.LinearMipmapLinearFilter,
});
const cubeCamera = new THREE.CubeCamera(0.1, 1000, cubeRenderTarget);
UV Channels
Every UV-mapped material texture samples the UV attribute chosen by texture.channel: 0 reads uv (the default), 1 reads uv1, 2 reads uv2, 3 reads uv3. So aoMap and lightMap work on the default uv set; a separately unwrapped set goes in uv1 with the texture pointed at it:
const aoTexture = new THREE.TextureLoader().load("ao.jpg");
const geometry = new THREE.BoxGeometry(1, 1, 1);
const uvAttribute = geometry.attributes.uv;
Texture Atlas
One image, many sprites, each selected with offset and repeat:
const atlas = await new THREE.TextureLoader().loadAsync("atlas.png");
atlas.colorSpace = THREE.SRGBColorSpace;
// filtering and mipmaps sample across sprite borders: leave padding around each sprite
// one clone per sprite: clones share the image source, so WebGLRenderer uploads it once
function spriteTexture(row, col
Standard Material Slots
Channel conventions worth knowing: aoMap reads red, roughnessMap reads green, metalnessMap reads blue (so one packed occlusion-roughness-metalness image works); alphaMap reads green.
const colorMap = new THREE.TextureLoader().load("color.jpg");
const emissiveMap = new THREE.TextureLoader().load("emissive.jpg");
const normalMap
alphaMap takes effect with transparent: true (blended) or alphaTest (cut out); displacementMap scales with displacementScale and displacementBias and wants a subdivided mesh; normalMapType defaults to TangentSpaceNormalMap, set ObjectSpaceNormalMap for object-space normal maps.
Disposal and Memory
texture.dispose() frees the GPU upload once no other undisposed texture shares it (the atlas clones above share one); the image object remains. Dispose only textures that no other material still uses:
function disposeMaterial(material) {
for (const key of Object.keys(material)) {
const value = material[key];
if (value && value.isTexture) {
value.dispose();
}
}
material.dispose();
}console.log(renderer.info.memory.textures); // texture count currently on the GPU
console.log(renderer.capabilities.maxTextureSize); // largest supported dimensionShare one texture instance across materials rather than loading per mesh. Non-power-of-two sizes are fine: WebGL 2 supports mipmaps and repeat wrapping on them.
WebGPU and TSL
import * as THREE from "three/webgpu";
import { texture, uv } from "three/tsl";
const renderer = new THREE.WebGPURenderer({ antialias:
TSL sampling: texture(map) uses uv() plus the texture's own offset/repeat/rotation; an explicit node takes over the coordinates entirely. The classic slots (map, normalMap, roughnessMap, aoMap) work unchanged on node materials; colorNode is for custom sampling.
import * as THREE from "three/webgpu";
import { texture, uv } from "three/tsl";
const map = new THREE.TextureLoader().load("diffuse.jpg");
map.colorSpace = THREE.SRGBColorSpace;
mesh.material.colorNode = texture
KTX2Loader.detectSupport(renderer) queries device features, so call it after await renderer.init(). For dynamic reflections use CubeRenderTarget (not WebGLCubeRenderTarget) with the same hide-update-show CubeCamera pattern.
import * as THREE from "three/webgpu";
const cubeRenderTarget = new THREE.CubeRenderTarget(256); // replaces WebGLCubeRenderTarget
const cubeCamera = new THREE.CubeCamera(0.1, 1000, cubeRenderTarget);
Common Mistakes
geometry.setAttribute("uv2", geometry.attributes.uv)→material.aoMap = aoTexture;: aoMap samples the attribute picked bytexture.channel(default 0,uv), so it needs no extra attribute anduv2is read only by textures whosechannelis 2; only a separate baked unwrap goes inuv1, withaoTexture.channel = 1.new RGBELoader()→new HDRLoader(): renamed from RGBELoader to HDRLoader in r180; the old class still runs but logs a deprecation warning.import { EXRLoader } from "three/examples/jsm/loaders/EXRLoader.js"→import { EXRLoader } from "three/addons/loaders/EXRLoader.js": the browser import maps mapthree/addons/to examples/jsm/ and define nothree/examples/key, so the examples path fails to resolve there.texture.encoding = THREE.sRGBEncoding→ : and the constant were removed; replaced them.
See Also
threejs-materials— material properties, blending, and physical materials beyond texture slots.threejs-loaders— loading managers, glTF models, and the loader family generally.threejs-shaders— custom GLSL texture sampling under WebGLRenderer.threejs-lighting— environment lighting and light units.threejs-asset-pipeline— encoding a model's textures to KTX2, WebP or AVIF with gltf-transform.