Textures & UVs
A texture is an image the GPU samples while drawing. Materials use textures for color (map), surface detail (normalMap), roughness, glow and more. In a shipped game most textures come from image files (TextureLoader, or compressed KTX2 files, see DRACO, KTX2 & Meshopt); in this lesson we make them in code, which is also handy for prototypes, procedural games and dynamic content such as scoreboards.
Where the image lands: UVs
Every vertex of a geometry carries a UV coordinate: u across and v up the texture, both from 0 to 1. The GPU interpolates UVs across each triangle and looks up the texture there. The built-in geometries come with sensible UVs (a box maps the whole image onto each face); models get theirs from the artist's UV unwrap in Blender.
UVs outside 0–1 are allowed. What happens there depends on the texture's wrapping mode, and texture.repeat / texture.offset transform UVs before the lookup. This model shows where a few UVs sample in an 8-pixel-wide texture:
// Which texel column does a u coordinate sample, for an 8-texel-wide texture?
const WIDTH = 8;
const wrap = {
ClampToEdge: (u) => Math.min(Math.max(u, 0), 1),
Repeat: (u) => u - Math.floor(u),
MirroredRepeat: (u) => { const f = u - 2 * Math.floor(u / 2); return f > 1 ? 2 - f : f; },
};
function texel(u, mode, repeat = 1, offset = 0) {
const w = wrap[mode](u * repeat + offset);
return Math.min(WIDTH - 1, Math.floor(w * WIDTH)); // nearest filtering
}
const us = [0.1, 0.5, 0.9, 1.3, 1.9, -0.2];
console.log('u: ', us.map((u) => String(u).padStart(4)).join(' '));
for (const mode of Object.keys(wrap)) {
console.log(mode.padEnd(16), us.map((u) => String(texel(u, mode)).padStart(4)).join(' '));
}
console.log('Repeat x3 ', us.map((u) => String(texel(u, 'Repeat', 3)).padStart(4)).join(' '));u: 0.1 0.5 0.9 1.3 1.9 -0.2
ClampToEdge 0 4 7 7 7 0
Repeat 0 4 7 2 7 6
MirroredRepeat 0 4 7 5 0 1
Repeat x3 2 4 5 7 5 3
Clamp-to-edge (the default) smears the border texels; RepeatWrapping tiles; mirrored repeat flips every other tile. To tile a floor texture four times, set both wrapS (u) and wrapT (v) to THREE.RepeatWrapping and texture.repeat.set(4, 4). Forgetting the wrap mode is the classic "my repeat does nothing, the edge is stretched" bug.
CanvasTexture: draw it with the 2D API
Any <canvas> can be a texture. Draw on it with the familiar 2D context, wrap it in THREE.CanvasTexture, and mark it as color data:
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
.label { position: fixed; bottom: 8px; color: #fff; font: 12px system-ui, sans-serif; text-shadow: 0 1px 2px #000 }</style>
<div class="label" style="left: 12%">colorSpace = SRGBColorSpace</div><div class="label" style="left: 58%">no colorSpace (wrong: washed out)</div>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1b2030');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 1.5, 6);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight('#fff', '#445', 1.5));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(2, 4, 5);
scene.add(sun);
// Draw a brick pattern with the 2D canvas API.
function brickCanvas() {
const c = document.createElement('canvas');
c.width = c.height = 256;
const g = c.getContext('2d');
g.fillStyle = '#d9d2c5'; // mortar
g.fillRect(0, 0, 256, 256);
const colors = ['#a0412d', '#b5523a', '#8f3a28', '#c0603f'];
for (let row = 0; row < 8; row++) {
for (let col = -1; col < 4; col++) {
g.fillStyle = colors[(row * 3 + col + 4) % colors.length];
g.fillRect(col * 64 + (row % 2) * 32 + 2, row * 32 + 2, 60, 28);
}
}
return c;
}
const good = new THREE.CanvasTexture(brickCanvas());
good.colorSpace = THREE.SRGBColorSpace; // the canvas holds sRGB colors
good.wrapS = good.wrapT = THREE.RepeatWrapping;
good.repeat.set(2, 2);
good.anisotropy = renderer.capabilities.getMaxAnisotropy();
const bad = good.clone();
bad.colorSpace = THREE.NoColorSpace; // what you get when you forget the line above
const geo = new THREE.BoxGeometry(2, 2, 2);
const left = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ map: good }));
const right = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ map: bad }));
left.position.x = -1.7;
right.position.x = 1.7;
scene.add(left, right);
renderer.setAnimationLoop((t) => {
left.rotation.y = right.rotation.y = t / 3000;
renderer.render(scene, camera);
});
</script>The right cube's bricks look pale and washed out: its texture's sRGB values are being treated as linear light values. Every color texture needs colorSpace = THREE.SRGBColorSpace. (TextureLoader doesn't set it for you; GLTFLoader sets it correctly on the textures of loaded models.) The Color Spaces & Tone Mapping lesson explains why.
DataTexture: raw pixels
THREE.DataTexture takes a typed array of pixel values. It's ideal for generated data: noise, height maps, lookup tables, or tiny pixel art. Here an 8 × 8 pixel-art tile is shown on two floors: nearest filtering (crisp pixels) on the left, linear (blurry) on the right.
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#10141e');
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 2.2, 5);
camera.lookAt(0, 0, -2);
// An 8x8 grass-and-flower tile, one character per pixel.
const art = [
'ggGggggG', 'gGggyggg', 'ggggggGg', 'gggGgggg',
'Ggggggrg', 'gggggggg', 'ggrggGgg', 'gGgggggg',
];
const palette = { g: [76, 140, 64], G: [58, 112, 50], y: [240, 210, 70], r: [220, 80, 90] };
const data = new Uint8Array(8 * 8 * 4);
art.forEach((row, y) => [...row].forEach((ch, x) => {
const i = ((7 - y) * 8 + x) * 4; // DataTexture rows start at the bottom
data.set([...palette[ch], 255], i);
}));
function tile(filter) {
const tex = new THREE.DataTexture(data, 8, 8, THREE.RGBAFormat);
tex.colorSpace = THREE.SRGBColorSpace;
tex.magFilter = filter; // when a texel covers many pixels
tex.minFilter = filter === THREE.NearestFilter ? THREE.NearestMipmapNearestFilter : THREE.LinearMipmapLinearFilter;
tex.generateMipmaps = true;
tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
tex.repeat.set(4, 6);
tex.needsUpdate = true; // DataTextures must be flagged once
return tex;
}
const floorGeo = new THREE.PlaneGeometry(3.2, 8);
[[THREE.NearestFilter, -1.7], [THREE.LinearFilter, 1.7]].forEach(([f, x]) => {
const floor = new THREE.Mesh(floorGeo, new THREE.MeshBasicMaterial({ map: tile(f) }));
floor.rotation.x = -Math.PI / 2;
floor.position.set(x, 0, -2);
scene.add(floor);
});
renderer.render(scene, camera);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.render(scene, camera);
});
</script>Filtering, mipmaps and anisotropy
| Setting | What it does | Game advice |
|---|---|---|
magFilter |
sampling when the texture is enlarged | LinearFilter (default) for photos/painted art; NearestFilter for pixel art |
minFilter |
sampling when it is shrunk | default LinearMipmapLinearFilter (trilinear) avoids shimmering |
generateMipmaps |
pre-computes half-size copies of the texture (mipmaps) | keep on for 3D surfaces; costs about 33% extra memory |
anisotropy |
sharper textures at grazing angles (floors, roads) | renderer.capabilities.getMaxAnisotropy() (often 16) for floors; costs some bandwidth |
Without mipmaps, a detailed texture far away sparkles as the camera moves, because each screen pixel samples a random texel. Mipmaps fix that by sampling a pre-shrunk copy. WebGL 2 can mipmap textures of any size, but power-of-two sizes (256, 512, 1024 …) are still the safe choice for compression formats and older devices.
Dynamic textures
A CanvasTexture can be redrawn any time: draw to its canvas and set texture.needsUpdate = true, which uploads it again. Good uses: a scoreboard in the world, a monitor showing text, a minimap. Upload only when the content changes (not every frame), and keep such canvases small: uploading a 2048 × 2048 texture is several megabytes of traffic.
function setScore(n) {
ctx.clearRect(0, 0, 256, 64);
ctx.fillText(`Score ${n}`, 128, 40);
scoreTexture.needsUpdate = true; // re-upload once
}Loading image files
In a real project, images come from files:
const loader = new THREE.TextureLoader();
const albedo = await loader.loadAsync('textures/crate_albedo.jpg');
albedo.colorSpace = THREE.SRGBColorSpace; // color data
const normal = await loader.loadAsync('textures/crate_normal.png'); // data: leave linear
const crate = new THREE.MeshStandardMaterial({ map: albedo, normalMap: normal });Textures are usually the biggest part of a game's memory: a 2048 × 2048 RGBA texture takes 16 MB of GPU memory uncompressed (21 MB with mipmaps), no matter how small the JPEG file was. Dispose textures you no longer need (texture.dispose()), and prefer GPU-compressed KTX2 textures for anything large.
Test yourself
You set texture.repeat.set(4, 4) but the texture is stretched with smeared edges instead of tiling. What is missing?
texture.needsUpdate = truetexture.wrapS = texture.wrapT = THREE.RepeatWrappingtexture.colorSpace = THREE.SRGBColorSpacegenerateMipmaps = false
Which filter settings keep pixel-art textures crisp up close?
magFilter = THREE.LinearFiltermagFilter = THREE.NearestFilteranisotropy = 16colorSpace = NoColorSpace
How much GPU memory does an uncompressed 2048 × 2048 RGBA texture use, without mipmaps?
- About 2 MB
- About 4 MB
- About 16 MB
- The size of the JPEG file