Import the GLTFLoader class
When a 3D object is modeled in an external tool such as Blender, it is possible to export it in several formats. One of these possibilities is the GLTF
format.
The file extensions of this format are .GBL
or .GLTF
.
Three.js does not offer a solution to natively load 3D models of this format. However, a class for this purpose is available in the official add-ons of the library :
import { GLTFLoader } from '../js/examples/jsm/loaders/GLTFLoader.js';
Use of the GLTFLoader class
The constructor of this class does not need any argument. To start, we create a GLTFLoader
type object.
var loader = new GLTFLoader();
Then, with the load
method, we load a GLB
or GLTF
file :
var loader = new GLTFLoader(); loader.load( '../Items/bluesword.glb', function ( gltf ) { [...] } );
This method requires two arguments :
GLB
orGLTF
file – The path to the file to be loaded- Callback – A callback function called at the end of the file loading
The following operations require the file to be loaded, to ensure this, the following operations are performed in the callback function.
We can now use the loaded file in our Three.js application !
sword = gltf.scene; // sword 3D object is loaded sword.scale.set(2, 2, 2); sword.position.y = 4;
The gltf
variable in parameter of the callback function is the result of the loading by the load
method.
The 3D object we are interested in is available in the scene
attribute of the gltf
variable. We can now use it as a classic 3D Mesh
Three.js object.
scene.add(sword);
Result and final code
/* * * We are using GLTFLoader to load the .glb 3D model * */ var loader = new GLTFLoader(); loader.load( '../Items/bluesword.glb', function ( gltf ) { sword = gltf.scene; // sword 3D object is loaded sword.scale.set(2, 2, 2); sword.position.y = 4; scene.add(sword); } );
Bonus – The animations included in the 3D model
It is also possible to include animated 3D models in the GLB
/ GLTF
format. To learn how to use these animations, I recommend you to read this publication :
Enjoy your reading !
We still have a lot to learn about loading 3D objects into Three.js !
In chapter 9 and 10 of the downloadable guide, we will discover the details of loading 3D objects, and all the related notions (dynamic shadows, animations …).
You can download the complete guide here :
[…] 23 juin 202125 août 2021 thomassifferlen 2 commentaires Available in English […]
[…] Load a 3D GLB / GLTF model with Three.js – GLTFLoader […]
[…] Load a 3D GLB / GLTF model with Three.js – GLTFLoader […]