Three.js for Creators: A Beginner's Guide to 3D Web Experiences

Using the TextureLoader

Section 7

Chapter 6: Loading External Assets: Models and Textures

Three.js for Creators: A Beginner's Guide to 3D Web ExperiencesChapter 6: Loading External Assets: Models and Textures

In the world of 3D graphics, textures are what bring our models to life. Think of them as the 'skin' or 'paint' we apply to our 3D objects, adding detail, color, and realism. In Three.js, the TextureLoader is your go-to tool for loading these image files and preparing them to be used on your meshes.

The TextureLoader is part of the three/examples/jsm/loaders/TextureLoader.js module. You'll need to import it into your project before you can use it. It's a straightforward process that involves creating an instance of the loader and then calling its load() method.

import { TextureLoader } from 'three/examples/jsm/loaders/TextureLoader.js';

const textureLoader = new TextureLoader();

The load() method takes a single argument: the URL of the image file you want to load. This can be a relative path or an absolute URL. The load() method is asynchronous, meaning it doesn't block the execution of your script while it waits for the image to download. Instead, it uses a callback function to handle the texture once it's ready.

The callback function receives the loaded Texture object as its argument. Inside this callback, you can then apply this texture to a material, which in turn is applied to a mesh. This is where the magic happens, and your 3D object gets its visual identity.

textureLoader.load(
  'path/to/your/image.jpg',
  (texture) => {
    // Texture has loaded successfully
    // You can now use the 'texture' object
    const material = new THREE.MeshBasicMaterial({ map: texture });
    const geometry = new THREE.BoxGeometry(1, 1, 1);
    const cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
  },
  (xhr) => { // Optional: Progress callback
    console.log((xhr.loaded / xhr.total * 100) + '% loaded');
  },
  (error) => { // Optional: Error callback
    console.error('An error happened:', error);
  }
);

The load() method also supports optional progress and error callbacks. The progress callback is useful for displaying loading progress to the user, especially for larger assets. The error callback is crucial for debugging, as it will log any issues encountered during the loading process, such as an invalid file path or network problems.

Once a texture is loaded, it's represented by a THREE.Texture object. This object has numerous properties that you can manipulate to control how the texture behaves. For example, you can set properties like wrapS, wrapT, repeat, offset, flipY, and minFilter, magFilter to fine-tune the texture's appearance and tiling on your model.

チャプターへ戻る