One of the most exciting aspects of building 3D web experiences is the ability to bring in pre-made 3D models created by artists and designers. This allows you to populate your scenes with complex objects without having to model them yourself in Three.js. Three.js supports a variety of 3D model formats, but the most common and recommended ones are glTF (.gltf and .glb). glTF is designed specifically for efficient transmission and loading of 3D scenes and models, making it ideal for the web.
To load a 3D model, we'll primarily use the GLTFLoader class provided by Three.js. This loader handles parsing the glTF file and creating the corresponding Three.js objects (meshes, materials, lights, etc.) for you. You'll need to include the GLTFLoader in your project, typically by downloading the file or using a CDN. You can find it in the examples/jsm/loaders/ directory of the Three.js repository.
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';Once you have the GLTFLoader imported, you can create an instance of it. Then, you use its load() method, providing the path to your glTF file. The load() method is asynchronous, meaning it will start loading the file in the background. It accepts three callback functions: one for progress tracking, one for handling successful loading, and one for handling errors.
const loader = new GLTFLoader();
loader.load(
'path/to/your/model.gltf', // URL to the model file
function ( gltf ) {
// Called when the model has been loaded successfully
console.log('Model loaded successfully!', gltf);
// The gltf object contains the loaded scene graph
// You can access the scene with gltf.scene
scene.add( gltf.scene );
},
function ( xhr ) {
// Called while loading is progressing
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
function ( error ) {
// Called when there is an error loading the model
console.error( 'An error happened:', error );
}
);The gltf object passed to the success callback is a GLTF object. The most important property for us is gltf.scene, which is a THREE.Scene object containing all the nodes, meshes, materials, and other elements that make up your 3D model. You can then add this gltf.scene directly to your main Three.js scene.