How to Use OBJLoader and MTLLoader in Three.js

This article explains how to load and render legacy 3D models in Three.js using OBJLoader and MTLLoader. You will learn how to import the necessary modules, load material files (.mtl) first, associate those materials with the geometry file (.obj), and add the fully textured 3D asset to your Three.js scene.

To load a legacy .obj file with its corresponding .mtl material textures in Three.js, you must load the materials first. Because the OBJ file format does not contain material properties or texture paths natively inside the geometry file, MTLLoader must parse the material definition file before OBJLoader can apply those textures to the loaded 3D mesh.

Step 1: Import the Loaders

First, import Three.js along with the specific loaders from the three/examples/jsm/loaders/ directory.

import * as THREE from 'three';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader.js';

Step 2: Set Up the Loading Sequence

Create an instance of MTLLoader to load the .mtl file. Once loaded, pre-load the materials and pass them to a new instance of OBJLoader using the setMaterials() method.

// Set up the scene, camera, and renderer first
const scene = new THREE.Scene();

// Initialize MTLLoader
const mtlLoader = new MTLLoader();

// Optional: Set base path for textures if they reside in a specific folder
mtlLoader.setPath('assets/models/');

// Load the material file
mtlLoader.load('model.mtl', (materials) => {
    materials.preload();

    // Initialize OBJLoader
    const objLoader = new OBJLoader();
    
    // Assign the loaded materials to the OBJLoader
    objLoader.setMaterials(materials);
    objLoader.setPath('assets/models/');

    // Load the OBJ model
    objLoader.load('model.obj', (object) => {
        // Add the textured model to your scene
        scene.add(object);
    }, 
    (xhr) => {
        console.log(`OBJ loading progress: ${(xhr.loaded / xhr.total * 100)}%`);
    }, 
    (error) => {
        console.error('An error occurred while loading the OBJ file:', error);
    });
}, 
(xhr) => {
    console.log(`MTL loading progress: ${(xhr.loaded / xhr.total * 100)}%`);
}, 
(error) => {
    console.error('An error occurred while loading the MTL file:', error);
});

Key Considerations for Legacy Files