glTF & GLTFLoader
glTF 2.0 (from the Khronos Group) is the standard file format for 3D on the web, often called "the JPEG of 3D". A glTF file holds a whole scene: node hierarchy, meshes, PBR materials, textures, cameras, skeletons and animations, stored the way GPUs want them, so loading is fast. Blender, Maya, 3ds Max, Substance and most asset stores export it. If you use one model format with Three.js, use this one.
The file formats
| Form | What it is | Use |
|---|---|---|
.gltf + .bin + images |
JSON description, a binary buffer file and texture files side by side | editing, inspecting, debugging |
.gltf with embedded data |
JSON with buffers as base64 data: URIs |
tiny examples (base64 is 33% larger) |
.glb |
one binary file: JSON chunk + binary chunk (textures inside) | shipping: one request, no base64 |
The JSON part is readable. Its main arrays reference each other by index:
| Array | Holds |
|---|---|
scenes, nodes |
the hierarchy; each node has a transform (translation, rotation quaternion, scale) and optionally a mesh, camera, skin and children |
meshes |
each mesh has primitives: attribute accessors (POSITION, NORMAL, TEXCOORD_0, …), indices, material |
materials |
metallic-roughness PBR: baseColorFactor, metallicFactor, roughnessFactor, texture references, emissiveFactor, alphaMode, doubleSided |
accessors → bufferViews → buffers |
typed views into the binary data: "36 VEC3 floats starting at byte 0 of buffer 0" |
animations |
channels (which node property) and samplers (keyframe times + values) |
skins, textures, images, samplers |
skeletons, texture references and their filtering |
glTF's conventions match Three.js: right-handed, +Y up, metres, models face +Z. Colors in baseColorFactor are linear; color textures are sRGB (and GLTFLoader tags them correctly for you).
Loading a model
In a project, you load a file with GLTFLoader. Everything comes back in one object:
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
const gltf = await loader.loadAsync('models/robot.glb');
// gltf.scene – a THREE.Group with the whole node hierarchy
// gltf.animations – an array of THREE.AnimationClip
// gltf.cameras, gltf.asset, gltf.parser (low-level access)
scene.add(gltf.scene);
// The callback form, with progress and errors:
loader.load('models/robot.glb',
(gltf) => scene.add(gltf.scene),
(event) => console.log(`${event.loaded} bytes loaded`),
(error) => console.error('could not load the robot:', error),
);The course's playgrounds can't fetch files, but GLTFLoader can also parse glTF that is already in memory: loader.parse(data, path, onLoad, onError) or await loader.parseAsync(data, path), where data is a JSON string or an ArrayBuffer (GLB). The example below builds a small glTF in JavaScript, a pedestal with a spinning crystal and a two-second animation, with the buffer embedded as a base64 data: URI, and loads it exactly as a downloaded file would be loaded:
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// ---------- 1. Write a glTF file in memory ----------
// Geometry data is borrowed from built-in shapes; any arrays would do.
const box = new THREE.BoxGeometry(1.2, 0.5, 1.2);
const gem = new THREE.OctahedronGeometry(0.45);
const chunks = [], bufferViews = [], accessors = [];
let byteLength = 0;
function addAccessor(array, type, count, withMinMax = false) {
const bytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
bufferViews.push({ buffer: 0, byteOffset: byteLength, byteLength: bytes.length });
chunks.push(bytes);
byteLength += bytes.length;
while (byteLength % 4) { chunks.push(new Uint8Array(1)); byteLength++; } // keep 4-byte alignment
const acc = { bufferView: bufferViews.length - 1, componentType: array instanceof Float32Array ? 5126 : 5123, count, type };
if (withMinMax) { // the spec requires min/max on POSITION
const n = type === 'VEC3' ? 3 : 1;
acc.min = [...Array(n)].map((_, k) => Math.min(...array.filter((_, i) => i % n === k)));
acc.max = [...Array(n)].map((_, k) => Math.max(...array.filter((_, i) => i % n === k)));
}
accessors.push(acc);
return accessors.length - 1;
}
const boxPrim = {
attributes: {
POSITION: addAccessor(box.attributes.position.array, 'VEC3', box.attributes.position.count, true),
NORMAL: addAccessor(box.attributes.normal.array, 'VEC3', box.attributes.normal.count),
},
indices: addAccessor(new Uint16Array(box.index.array), 'SCALAR', box.index.count),
material: 0,
};
const gemPrim = {
attributes: {
POSITION: addAccessor(gem.attributes.position.array, 'VEC3', gem.attributes.position.count, true),
NORMAL: addAccessor(gem.attributes.normal.array, 'VEC3', gem.attributes.normal.count),
},
material: 1,
};
// Animation: keyframe times and Y-axis rotation quaternions (0°, 180°, 360°).
const times = addAccessor(new Float32Array([0, 1, 2]), 'SCALAR', 3);
accessors[times].min = [0]; accessors[times].max = [2];
const rots = addAccessor(new Float32Array([0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, -1]), 'VEC4', 3);
const bin = new Uint8Array(byteLength);
let at = 0;
for (const c of chunks) { bin.set(c, at); at += c.length; }
let binary = '';
for (const b of bin) binary += String.fromCharCode(b);
const gltfJson = {
asset: { version: '2.0', generator: 'ExcelTAD lesson' },
scene: 0,
scenes: [{ nodes: [0] }],
nodes: [
{ name: 'Pedestal', mesh: 0, children: [1] },
{ name: 'Crystal', mesh: 1, translation: [0, 0.85, 0] },
],
meshes: [{ name: 'PedestalMesh', primitives: [boxPrim] }, { name: 'CrystalMesh', primitives: [gemPrim] }],
materials: [
{ name: 'Stone', pbrMetallicRoughness: { baseColorFactor: [0.45, 0.42, 0.38, 1], metallicFactor: 0, roughnessFactor: 0.9 } },
{ name: 'Crystal', pbrMetallicRoughness: { baseColorFactor: [0.2, 0.75, 1, 1], metallicFactor: 0.1, roughnessFactor: 0.2 }, emissiveFactor: [0.02, 0.15, 0.25] },
],
animations: [{
name: 'Spin',
samplers: [{ input: times, output: rots, interpolation: 'LINEAR' }],
channels: [{ sampler: 0, target: { node: 1, path: 'rotation' } }],
}],
buffers: [{ byteLength, uri: 'data:application/octet-stream;base64,' + btoa(binary) }],
bufferViews,
accessors,
};
const text = JSON.stringify(gltfJson);
console.log(`glTF JSON: ${text.length} characters, binary buffer: ${byteLength} bytes`);
// ---------- 2. Load it like any downloaded model ----------
const gltf = await new GLTFLoader().parseAsync(text, '');
const model = gltf.scene;
model.traverse((o) => console.log(`${' '.repeat(o.parent && o.parent !== model ? 2 : o === model ? 0 : 1)}${o.type} "${o.name}"${o.isMesh ? ` (${o.material.type} "${o.material.name}")` : ''}`));
console.log('animations:', gltf.animations.map((c) => `${c.name} ${c.duration}s, ${c.tracks.length} track: ${c.tracks[0].name}`).join(', '));
// ---------- 3. Show and animate it ----------
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('#141924');
scene.add(new THREE.HemisphereLight('#dfe9ff', '#3a3530', 1.5));
const sun = new THREE.DirectionalLight('#fff', 2.5);
sun.position.set(2, 4, 3);
scene.add(sun);
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 1.6, 4);
camera.lookAt(0, 0.6, 0);
// Three copies: clone() shares geometry and materials, so they are cheap.
const mixers = [-1.8, 0, 1.8].map((x, i) => {
const copy = i === 1 ? model : model.clone();
copy.position.x = x;
scene.add(copy);
const mixer = new THREE.AnimationMixer(copy);
mixer.clipAction(gltf.animations[0]).play();
mixer.setTime(i * 0.3); // offset each copy a little
return mixer;
});
const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
timer.update(t);
const dt = Math.min(Math.max(timer.getDelta(), 0), 0.1);
for (const m of mixers) m.update(dt);
renderer.render(scene, camera);
});
</script>The console shows what the loader produced: a Group for the glTF scene, an Object3D per node (a node with exactly one mesh becomes the Mesh itself), MeshStandardMaterials named after the glTF materials, and an AnimationClip whose track name Crystal.quaternion targets the node by name. The AnimationMixer & Clips lesson explains how to play clips.
Working with a loaded model
const gltf = await loader.loadAsync('models/level.glb');
const level = gltf.scene;
level.traverse((o) => {
if (o.isMesh) {
o.castShadow = o.receiveShadow = true; // shadow flags are not stored in glTF
}
});
const door = level.getObjectByName('Door_01'); // node names from Blender survive the export
const spawn = level.getObjectByName('PlayerSpawn').position; // an empty used as a markerHabits that save time:
- Name things in Blender. Empties named
Spawn_Player,Coin_03,Trigger_Exitare an easy level editor; read them withgetObjectByNameor by scanning names intraverse. Custom properties exported from Blender arrive inobject.userData. - Check the scale. Blender exports metres; if a model is 100× too big, the source used centimetres. Fix it in the source file, not with
scalein code. - Cloning.
model.clone()is fine for static models (geometry and materials are shared). For skinned (rigged) characters useSkeletonUtils.clone(model)fromthree/addons/utils/SkeletonUtils.js, which rebinds the copy's bones; a plain clone keeps deforming with the original's skeleton. - Disposing. Removing a model from the scene doesn't free GPU memory. When a level unloads, traverse it and dispose each geometry, material and texture (unless other models still use them).
- Validate. The Khronos glTF Validator and the online glTF viewers (for example gltf-viewer.donmccurdy.com) show quickly whether a broken model is a file problem or a code problem.
Exporting
GLTFExporter (three/addons/exporters/GLTFExporter.js) turns a Three.js scene back into glTF or GLB, useful for level editors built in the browser, saving procedurally generated models, or bug reports:
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
const glb = await new GLTFExporter().parseAsync(scene, { binary: true }); // ArrayBufferTest yourself
Which glTF form is best for shipping a game's models?
.gltfwith base64-embedded buffers.glb: one binary file with the JSON and data inside.obj+.mtl- A JSON file per mesh
You clone a rigged character with model.clone() and play an animation on the copy, but the copy doesn't move correctly. What should you use?
model.copy()SkeletonUtils.clone(model)structuredClone(model)- Load the file again for every copy
Which property is NOT stored in a glTF file and must be set in code after loading?
- Node names
- Material base colors
castShadow/receiveShadow- Animations