One of the most common tasks when creating 3D web experiences is bringing in pre-made models and textures. Three.js offers a variety of loaders for different file formats. Among the most popular and versatile is the GLTFLoader, designed to work with the glTF (GL Transmission Format) file format. glTF is often referred to as the 'JPEG of 3D' because it's optimized for efficient transmission and loading of 3D scenes and models.
Why glTF? It's a modern, open standard that supports PBR (Physically Based Rendering) materials, animations, and a wide range of features, making it ideal for web-based 3D. The GLTFLoader in Three.js makes it incredibly straightforward to load these assets into your scene.
To use the GLTFLoader, you first need to include it in your project. This is typically done by adding it as a script tag in your HTML or by importing it if you're using a module bundler like Webpack or Parcel.
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
// Or if not using modules, you might include it via a script tag in your HTML:
// <script src="/path/to/three/examples/js/loaders/GLTFLoader.js"></script>Once imported, you'll create an instance of the GLTFLoader and then use its load method, providing the path to your glTF file.
const loader = new GLTFLoader();
loader.load(
'/path/to/your/model.gltf',
(gltf) => {
// Called when the model is loaded successfully
console.log('GLTF model loaded successfully!');
// The loaded gltf object contains your scene, meshes, materials, animations, etc.
// You can access the scene root like this:
const model = gltf.scene;
scene.add(model);
// If your glTF file contains animations, you can access them too:
const animations = gltf.animations;
if (animations && animations.length > 0) {
// Handle animations here (e.g., set up an AnimationMixer)
console.log('Animations found!');
}
},
(xhr) => {
// Called while loading is in progress (optional)
console.log((xhr.loaded / xhr.total) * 100 + '% loaded');
},
(error) => {
// Called when loading fails (optional)
console.error('An error happened while loading the model:', error);
}
);The load method takes up to three arguments: the URL of the glTF file, a success callback function, and an optional progress callback, and an optional error callback. The success callback receives a gltf object, which is the primary way you'll interact with your loaded asset. This object typically contains a scene property, which is a Three.js Object3D representing the root of your loaded model. You can then add this scene object to your main Three.js scene.