In the world of 3D graphics, applying an image to the surface of a 3D model is known as texture mapping. Think of it like wallpaper for your 3D objects. Without textures, most 3D models would appear as plain, monochromatic shapes, lacking the detail and realism that makes them visually appealing. Three.js makes this process straightforward by utilizing texture mapping and UV coordinates.
Texture mapping involves taking a 2D image (the texture) and projecting it onto the 3D surface of an object. However, a 3D object's geometry isn't inherently aware of how to map a 2D image onto its complex surfaces. This is where UV coordinates come into play.
UV coordinates are a special set of 2D coordinates associated with each vertex of a 3D model. They essentially 'unwrap' the 3D surface of the model into a 2D plane, much like unfolding a cardboard box to lay it flat. The 'U' and 'V' axes represent the horizontal and vertical dimensions of this flattened texture space, analogous to the X and Y axes in a standard 2D image.
When you load a texture in Three.js, you create a THREE.Texture object. This object holds the image data. Then, you assign this texture to the map property of a material. The map property tells the material to use this texture for its surface color. The magic happens because Three.js automatically uses the UV coordinates defined within the model's geometry to determine how to sample colors from the texture and apply them to each part of the 3D surface.
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('path/to/your/texture.jpg');
const material = new THREE.MeshBasicMaterial({ map: texture });
// Assuming you have a geometry object named 'geometry'
const mesh = new THREE.Mesh(geometry, material);The UV coordinates for a model are typically exported from 3D modeling software (like Blender, Maya, or 3ds Max) along with the model's geometry. When you load a model using a loader (e.g., GLTFLoader, OBJLoader), these UV coordinates are preserved and made available within the loaded geometry. If a model doesn't have UV coordinates, texture mapping won't work as expected, and the texture might appear distorted or not at all.
graph TD
A[3D Model Geometry] --> B{Vertices with UV Coordinates};
B --> C[Texture Image];
C -- Mapped using UVs --> D[3D Object Surface];
D --> E[Rendered Scene];