The MaterialLoader.load()
method is a feature of the Three.js library that allows users to load and parse external materials created using the Three.js material format (.mtl
files). This method is useful for users who want to create more complex scenes, as the MaterialLoader
makes it possible to apply custom materials to their 3D models with ease.
MaterialLoader.load(url: string, onLoad?: function, onProgress?: function, onError?: function) : undefined
This method takes in four parameters, which are described as follows:
url
- the URL of the .mtl
file to be loaded.onLoad
(optional) - a callback function that is executed once the material has been loaded successfully. The loaded material is passed as a single argument to the callback function. If no callback is provided, the material is simply returned by the load()
method.onProgress
(optional) - a callback function that is executed while the material is being loaded. The number of bytes loaded so far and the total number of bytes are passed to the callback function as arguments.onError
(optional) - a callback function that is executed if an error occurs while loading the material.Here is an example usage of the MaterialLoader.load()
method:
const loader = new THREE.MaterialLoader();
loader.load(
'models/materials.mtl',
(material) => {
console.log('Material loaded successfully:', material);
// Use the loaded material to create and apply custom materials to 3D models
// ...
},
(xhr) => {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
(error) => {
console.error('An error occurred while loading the material:', error);
}
);
In the example above, we create a new MaterialLoader
instance and use it to load the materials.mtl
file. Once the material is loaded successfully, we log a message to the console and then create and apply the loaded material to our 3D models. If an error occurs while loading the material, we log an error message to the console.
It is important to note that the MaterialLoader.load()
method requires an instance of the THREE.MaterialLoader
class, which can be imported using the following code:
import { MaterialLoader } from 'three';
Additionally, MaterialLoader.load()
is an asynchronous method, meaning that it does not block the main thread while the material is being loaded. As a result, it is important to use callback functions to handle the loaded material and any errors that may occur.