Three.js University GLB GLTF load

Load a 3D GLB / GLTF model with Three.js – GLTFLoader

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 or GLTF 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 !

Feel free to download the complete Three.js University guide to progress even faster !

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 …).

Three.js University Complete Guide – 3D Models
Three.js University Complete Guide – 3D Models

You can download the complete guide here :

3 comments

Comments are closed.