Load Image Texture using Three.js TextureLoader
This article provides a straightforward guide on how to load external
image files and apply them as textures to 3D objects in Three.js using
the TextureLoader class. You will learn how to instantiate
the loader, load an image asynchronously, apply it to a material, and
handle potential cross-origin (CORS) issues when loading images from
external domains.
To load an external image as a texture in Three.js, you use the
THREE.TextureLoader class. This built-in utility handles
the asynchronous loading of images (such as PNG, JPG, or WebP) and
returns a THREE.Texture object that can be mapped onto 3D
geometries.
Step 1: Instantiate the TextureLoader
First, create an instance of the TextureLoader:
const textureLoader = new THREE.TextureLoader();Step 2: Load the Texture and Apply It to a Material
Use the .load() method of the TextureLoader
instance. This method takes the image URL as its first argument and
returns a texture object immediately. You can assign this texture
directly to the map property of a material (like
MeshBasicMaterial or MeshStandardMaterial).
Three.js will automatically update the 3D object in the renderer once
the image finishes downloading.
// Load the image file
const texture = textureLoader.load('path/to/your/image.jpg');
// Create a material and assign the texture
const material = new THREE.MeshBasicMaterial({
map: texture
});Step 3: Create the Mesh
Apply the material containing your newly loaded texture to a geometry, create a mesh, and add it to your scene:
const geometry = new THREE.BoxGeometry(1, 1, 1);
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);Handling Callback Functions (Optional)
The .load() method accepts optional callback functions
to track when the image successfully loads or fails:
textureLoader.load(
'path/to/your/image.jpg',
function (loadedTexture) {
// Triggers when the texture is successfully loaded
console.log('Texture loaded successfully');
},
undefined, // Progress callback (not supported by TextureLoader)
function (error) {
// Triggers if there is an error loading the image
console.error('An error occurred while loading the texture', error);
}
);Important: Resolving Cross-Origin (CORS) Issues
If you are loading images from an external server rather than your
local domain, browsers may block the image due to CORS security
policies. To allow cross-origin image loading, configure the loader’s
cross-origin setting before calling .load():
textureLoader.setCrossOrigin('anonymous');