Loading glTF and GLB Models

Load glTF and GLB models with GLTFLoader and handle progress, errors, animations, resource paths, and Draco and Meshopt compression.

🎯 Introduction

By the end of this article, you will be able to load real glTF/GLB models, handle success, progress, and failure states, traverse model nodes, and understand the roles of Draco, Meshopt, and resource paths.

🧱 Why prefer glTF?

glTF is a 3D asset format designed for real-time rendering. It describes nodes, meshes, materials, textures, and animations. A .gltf asset typically consists of a JSON file and external resources. A .glb packages these into a binary file that is easier to manage during deployment.

This course uses Three.js 0.185.1. The loader is an add-on:

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

const loader = new GLTFLoader();
loader.load(
    '/models/avocado.glb',
    (gltf) => {
        const model = gltf.scene;
        scene.add(model);
    },
    (event) => {
        if (event.total) {
            console.log(`Loading progress: ${Math.round(event.loaded / event.total * 100)}%`);
        }
    },
    (error) => {
        console.error('Failed to load model', error);
    }
);

gltf.scene is the model's root node. Avoid adding an arbitrary child directly to the scene. Once added, the model's position, scale, and name can be set like any other Object3D.

This example uses the Avocado model, whose flesh, pit, and skin details come from its included textures. The demo loads /models/avocado.glb, uniformly scales and centers it using its bounding box, and displays its materials under soft ambient lighting.

Provided by Microsoft and included in Khronos glTF Sample Assets, the asset is licensed under CC0. To reproduce the example, download the GLB and place it in your project's public/models/ directory.

Loading the model

📦 Preparing and automatically fitting models

gltf.scene.name = 'avocado';
gltf.scene.traverse((object) => {
    if (!object.isMesh) return;
    object.castShadow = true;
    object.receiveShadow = true;
    object.userData.modelId = 'avocado-01';
});

const box = new THREE.Box3().setFromObject(gltf.scene);
const size = box.getSize(new THREE.Vector3());
const maxSize = Math.max(size.x, size.y, size.z);
gltf.scene.scale.setScalar(2.8 / maxSize);

const scaledBox = new THREE.Box3().setFromObject(gltf.scene);
const center = scaledBox.getCenter(new THREE.Vector3());
gltf.scene.position.sub(center);

This code names the root for later lookup, adds shadow settings and an application ID to each mesh, finds the model's largest dimension using a bounding box, and scales it to approximately 2.8 Three.js units. setScalar changes x, y, and z together, preserving proportions without flattening the model. Recalculating the bounding box after scaling and subtracting its center centers the model.

In real projects, check the model's units, orientation, and origin first. Calculate a bounding box before automatic scaling, and calculate it again after scaling if you need to reposition the model.

🧰 Draco, Meshopt, and path issues

Draco and Meshopt compress model data, reducing vertex data that must be downloaded or decoded. They are compression schemes within glTF/GLB rather than new model formats, so the browser needs the corresponding decoder:

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

const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('/draco/');
loader.setDRACOLoader(dracoLoader);

The decoder directory must be accessible from the deployed page. Meshopt is typically configured with the appropriate decoder on GLTFLoader, depending on the export tool and Three.js version. If a model appears blank, check model, texture, and decoder requests in the browser's Network panel first.

Model loading does not automatically resolve cross-origin restrictions. The model server must permit access from the page's origin, and texture paths referenced inside the model must be correct.

Models may come from third-party platforms whose download buttons and directory structures change. The paths here illustrate code organization. Use the actual model and decoder paths in your project.

🧾 Summary

  • glTF targets real-time rendering; GLB packages assets into a single file.
  • gltf.scene is the usual entry point in the GLTFLoader success callback.
  • Traverse loaded meshes to set shadows, names, and application data consistently.
  • Box3 helps center models and frame them with a camera.
  • Draco and Meshopt compress assets but require correct decoder path configuration.
  • Check static paths and cross-origin settings for models, textures, and decoders.

❓ Questions and answers

Q1: Should I choose .gltf or .glb?

.glb is simpler to deploy and transfer. .gltf makes it easier to inspect JSON, textures, and binary data separately. Choose based on how your project manages assets.

Q2: What if the model loads but textures do not appear?

Check relative texture paths inside the glTF, filename case on the server, and Network request statuses, rather than checking only the main model file.

Q3: Why is the model invisible?

Check that the success callback runs, the model is added to the scene, its position and scale are appropriate, the camera points at it, and any required decoder is configured.

🧪 Exercise

Prepare a browser-accessible /models/robot.glb. Load it with GLTFLoader, traverse all meshes to enable castShadow, and use Box3 to move the model to the origin.

// Write your code here

🎉 Loading real models is an important step from practice scenes to product pages. Next, you will animate objects and models.