Skip to content

GLTFloader

Import

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

// or if your environment supports the `addons` alias,

import { GLTFLoader } from 'three/addons/loaders/GLTFLoader'

Video Lecture

Section Video Links
GLTFloader : Part 1 GLTFloader : Part 1 GLTFloader : Part 1
GLTFloader : Part 2 GLTFloader GLTFloader : Part 2

Description

We can also load pre-built 3D models into our scene. In this example, I will use the useLoader hook to load a glTF model, by passing the Threejs GLTFloader module into the useLoader.

The glTF format,

  • is a specification for the efficient transmission and loading of 3D scenes and models.
  • Minimizes both the size of 3D assets, and the runtime processing needed to unpack and use those assets.
  • The exported asset may contain one or more scenes, meshes, materials, textures, skins, skeletons, morph targets, animations, lights and cameras.

Assets can be provided in either JSON (.gltf) or binary (.glb) format. Textures encoded in a .gltf JSON file are encoded using Base64, which can increase the payload by about 33%. So prefer to use the .glb binary export option.

In this lesson, we will use Blender to quickly create a 3d model, export it as binary glTF file and view it in our Three.js scene.

We will also experiment with some Blender material settings and see how they translate into the Three.js scene.

If you don't want to create the model in Blender, then you can download the final model as shown in this video from monkey.zip. Then extract the contents into the folder ./public/models/.

./src/App.jsx

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { Stats, OrbitControls, Circle } from '@react-three/drei'
import { Canvas, useLoader } from '@react-three/fiber'
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader'

export default function App() {
  const gltf = useLoader(GLTFLoader, '/models/monkey.glb')

  return (
    <Canvas camera={{ position: [-0.5, 1, 2] }} shadows>
      <directionalLight
        position={[3.3, 1.0, 4.4]}
        castShadow
        intensity={Math.PI * 2}
      />
      <primitive
        object={gltf.scene}
        position={[0, 1, 0]}
        children-0-castShadow
      />
      <Circle args={[10]} rotation-x={-Math.PI / 2} receiveShadow>
        <meshStandardMaterial />
      </Circle>
      <OrbitControls target={[0, 1, 0]} />
      <axesHelper args={[5]} />
      <Stats />
    </Canvas>
  )
}

Working Example

<>
Loading Models docs.pmnd.rs
GLTFLoader threejs.org sbcode.net
THREE.Group threejs.org

GitHub Branch

git clone https://github.com/Sean-Bradley/React-Three-Fiber-Boilerplate.git
cd React-Three-Fiber-Boilerplate
git checkout glTFLoader
npm install
npm start