Using glTF (GL Transmission Format) models in Three.js is a common and efficient way to display 3D content on the web. glTF is often referred to as the "JPEG of 3D" due to its optimization for web delivery.
GLTFLoaderTo load glTF models in Three.js, you primarily use the GLTFLoader class, which is part of the Three.js examples. It needs to be imported explicitly.
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
The loader.load method takes the model's URL, a callback for when the model is loaded, an optional callback for progress updates, and an optional callback for error handling.
import *s THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// Scene, Camera, Renderer setup (assuming these are already defined)
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Add some basic lighting to see the model
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1).normalize();
scene.add(directionalLight);
camera.position.z = 5;
const loader = new GLTFLoader();
loader.load(
// resource URL (replace with your model's path)
'path/to/your_model.gltf', // or .glb
// called when the resource is loaded
function (gltf) {
scene.add(gltf.scene);
// Optional: Access animations if present
// if (gltf.animations && gltf.animations.length) {
// const mixer = new THREE.AnimationMixer(gltf.scene);
// gltf.animations.forEach((clip) => {
// mixer.clipAction(clip).play();
// });
// // Remember to update the mixer in your animation loop
// }
},
// called while loading is in progress
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
// called when loading has errors
function (error) {
console.error('An error happened', error);
}
);
// Animation loop (essential for rendering)
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
.gltf) or binary (.glb) format. Binary .glb files are self-contained.DRACOLoader and set it on your GLTFLoader instance.scale and position properties of gltf.scene after loading.THREE.AnimationMixer and THREE.Clock to play these animations.