Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Textures and Loading Models

Loading glTF Models in Three.js

Load 3D models in Three.js with GLTFLoader: glTF vs GLB, scene graph traversal, centering and scaling, Draco and KTX2 compression, and exporting your own glTF.

Building every shape from boxes and spheres gets you through tutorials, but real projects use models made in Blender, Maya or downloaded from asset libraries. For the web, the format to use is glTF (GL Transmission Format), sometimes called "the JPEG of 3D". It was designed for fast loading and rendering, it stores meshes, materials, textures, skeletons and animations, and Three.js supports it directly through GLTFLoader.

This lesson explains the format, loads a model with the loader, shows how to inspect and fit it into your scene, and covers compression. To keep every example self-contained, the models here are created in code and travel through the real glTF pipeline: we write a tiny glTF by hand and we export a Three.js scene to glTF and load it back.

glTF and GLB

A glTF asset can be delivered in two ways:

  • .gltf: a JSON description of the scene, usually with separate .bin (geometry) and image files next to it. Easy to inspect, several requests.
  • .glb: the same data packed into one binary file. One request, usually what you ship.

Inside, a glTF file has a scene graph (scenes, nodes), meshes made of primitives, materials in PBR metallic-roughness form (the same model as MeshStandardMaterial), textures, animations and skins. Because the material model matches, models usually look right the moment they load, as long as the scene has an environment or lights.

flowchart LR
  A["Blender / Maya"] -->|"export"| B["model.glb"]
  B -->|"GLTFLoader"| C["gltf.scene (Group)"]
  C --> D["scene.add(...)"]
  B -.-> E["gltf.animations"]
  B -.-> F["gltf.cameras"]

The loader returns an object with scene, animations, cameras and more, not just a mesh.

Basic usage

JavaScript
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const loader = new GLTFLoader();
loader.load(
  'models/robot.glb',
  (gltf) => scene.add(gltf.scene),          // success
  (event) => console.log(event.loaded / event.total), // progress (may be 0 total)
  (error) => console.error(error)           // failure
);

// or with async/await
const gltf = await loader.loadAsync('models/robot.glb');
scene.add(gltf.scene);

gltf.scene is a Group you add like any other object. gltf.animations is an array of AnimationClips (see keyframe animation). Your page must serve the file over HTTP; loading from a file:// address fails because of browser security rules.

Parsing a glTF without a network request

GLTFLoader.parse(data, path, onLoad, onError) takes the file contents directly, as a string (for .gltf) or an ArrayBuffer (for .glb). That is useful for models received from an upload, a fetch, or a database. Here is a glTF written entirely by hand: one triangle with its geometry embedded as base64.

Writing and parsing a glTF by hand

Notice what the loader did for you: it created a Mesh, a MeshStandardMaterial with the right color and roughness, and even computed flat normals, because the glTF has no NORMAL attribute.

Inspecting what you loaded

You rarely know a downloaded model's structure in advance. traverse visits every descendant:

JavaScript
gltf.scene.traverse((obj) => {
  if (obj.isMesh) {
    obj.castShadow = true;
    obj.receiveShadow = true;
    console.log(obj.name, obj.material.name);
  }
});

Typical jobs for a traverse: enable shadows, find a mesh by name for interaction, swap a material, or collect everything that needs to be disposed later. You can also fetch a single part with gltf.scene.getObjectByName('Wheel_FL'); names come from the file, so ask the 3D artist for stable names.

Fitting a model into view

Models arrive in whatever unit and position the artist used: one may be 0.02 units tall, the next one 400. A Box3 measures the model so you can center and scale it:

JavaScript
const box = new THREE.Box3().setFromObject(model);
const size = box.getSize(new THREE.Vector3());
const center = box.getCenter(new THREE.Vector3());

model.position.sub(center);                 // move center to origin
model.scale.setScalar(2 / Math.max(size.x, size.y, size.z)); // longest side = 2 units

Do the translation first (using the unscaled box), or wrap the model in a parent Group and scale the group, to avoid confusing yourself about pivots.

Round trip: export a scene, load it back

GLTFExporter writes Three.js objects to glTF. That makes it a convenient save format for editors and the best way to see the whole pipeline without a file server. The next example builds a small named scene, exports it to glTF JSON, parses that JSON again, and fits the result to the view.

Export to glTF, load it back, fit it

Without the fitting step this snowman would be 300 units from the camera and invisible. Checking size and center in the console is the first thing to do when "my model doesn't show up".

Compression: Draco, Meshopt and KTX2

Large models can weigh megabytes. Three.js supports three standard ways to shrink them:

Technology Shrinks Loader setup
Draco Geometry (often 5 to 10 times smaller) DRACOLoader + loader.setDRACOLoader(...)
Meshopt Geometry and animation, fast decoding loader.setMeshoptDecoder(MeshoptDecoder)
KTX2 / Basis Textures, stays compressed in GPU memory KTX2Loader + loader.setKTX2Loader(...)
JavaScript
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';

const draco = new DRACOLoader();
draco.setDecoderPath('/libs/draco/');      // folder with the decoder files
const loader = new GLTFLoader();
loader.setDRACOLoader(draco);

The command line tool gltf-transform (or the online glTF viewers' optimizers) applies these to existing files. Draco decoding runs in a worker, so it does not freeze your page.

Common problems

  • The model is black: there are no lights and no scene.environment. glTF materials are PBR.
  • The model is huge or tiny, or invisible: measure with Box3 and fit it.
  • Textures look wrong: glTF texture color spaces are handled by the loader; do not reassign them.
  • Shadows missing: loaded meshes have castShadow and receiveShadow off by default; set them in a traverse.
  • Memory leaks when swapping models: dispose geometries, materials and textures of the old model (see performance fundamentals).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between .gltf and .glb?

    Both hold the same glTF data. A .gltf is JSON with separate resources; a .glb bundles everything into one binary, which means fewer requests.
  2. 2. What does GLTFLoader return to the success callback?

    You get a result object; gltf.scene is a Group to add to your scene and gltf.animations holds the clips.
  3. 3. Your loaded model does not appear, though there are no errors. What should you check first?

    Models often come in unusual units or far from the origin. Measure it with Box3 and center or scale it.
  4. 4. Which technology compresses the geometry of a glTF model with a decoder loaded through DRACOLoader?

    Draco compresses mesh geometry. KTX2 compresses textures, and Meshopt is another geometry option.

Summary

  • glTF is the web's standard 3D format; GLB is its single-file form.
  • GLTFLoader returns { scene, animations, cameras, ... }; add gltf.scene to your scene.
  • traverse and getObjectByName let you enable shadows, change materials and find parts.
  • Use Box3 to measure, center and scale models.
  • GLTFLoader.parse loads from memory, and GLTFExporter saves scenes to glTF.
  • Draco, Meshopt and KTX2 shrink downloads; light your model with an environment.

Next: Other Model Formats and the LoadingManager