Texture loading and mapping

Back to Modules

Texture Loading and Mapping in Three.js

Loading and mapping textures like diffuse, bump, and normal maps is crucial for adding visual detail and realism to 3D objects in Three.js. This process primarily involves using the THREE.TextureLoader to load image files and then assigning these loaded textures to specific properties of a material, most commonly THREE.MeshStandardMaterial for physically based rendering (PBR).

1. Texture Loading

To load any texture in Three.js, you use the THREE.TextureLoader class. This loader handles the asynchronous loading of image files and provides a Texture object that can be applied to materials.

import *s THREE from 'three';

const loader = new THREE.TextureLoader();

// Load a texture with an optional callback for when it's loaded
const diffuseTexture = loader.load(
    'path/to/your/diffuse_map.jpg',
    function (texture) {
        console.log('Diffuse texture loaded:', texture);
    },
    undefined, // onProgress callback (not supported by TextureLoader)
    function (err) {
        console.error('An error occurred loading the diffuse texture:', err);
    }
);

2. Diffuse Map (Color Map)

The diffuse map, often referred to as the color map or albedo map, defines the base color of the material. It's the most fundamental texture and is assigned to the map property of a material.

const material = new THREE.MeshStandardMaterial({
    map: diffuseTexture, // Assign the loaded diffuse texture to the 'map' property
});

3. Bump Map

A bump map is a grayscale image that creates the illusion of surface irregularities and depth by altering the perceived lighting across the surface. It does not, however, modify the actual geometry of the object.

const bumpTexture = loader.load('path/to/your/bump_map.jpg');

const material = new THREE.MeshStandardMaterial({
    map: diffuseTexture,
    bumpMap: bumpTexture, // Assign the loaded bump texture
    bumpScale: 0.5,      // Adjust the intensity of the bump effect (default is 1)
});

4. Normal Map

A normal map is an RGB image that provides more detailed and accurate surface normal information than a bump map. The red, green, and blue channels of the normal map correspond to the X, Y, and Z components of the surface normal, respectively. Like bump maps, normal maps simulate depth and detail without increasing the polygon count of the geometry.

const normalTexture = loader.load('path/to/your/normal_map.jpg');

const material = new THREE.MeshStandardMaterial({
    map: diffuseTexture,
    normalMap: normalTexture, // Assign the loaded normal texture
    normalScale: new THREE.Vector2(1, 1), // Adjust the intensity of the normal map effect
});

Example: Applying Textures

This example demonstrates how to load and apply a diffuse texture to a cube. For bump and normal maps, you would follow a similar loading process and assign them to their respective material properties.