Skip to main content

Archive

Show more

Materials and Textures in Three.js

Materials and Textures in Three.js

In Three.js, materials and textures are essential components for defining the appearance of 3D objects in your scene. Materials determine how light interacts with surfaces, while textures provide visual details such as colors, patterns, and images.


1. Materials

Three.js provides various types of materials, each with different properties and effects:

  • MeshBasicMaterial: A simple material that is unaffected by lights.
  • MeshLambertMaterial: A material that reacts to lights with diffuse reflection, suitable for matte surfaces.
  • MeshPhongMaterial: A material that reacts to lights with specular reflection, suitable for shiny surfaces.
  • MeshStandardMaterial: A physically-based material that offers a balance between performance and realism.
  • MeshPhysicalMaterial: A material that simulates real-world physical properties such as metalness and roughness.

Each material type has properties that can be adjusted to control factors like color, opacity, emissive color, roughness, and metalness.


2. Textures

Textures are images applied to the surfaces of 3D objects to add visual detail and realism. Three.js supports various types of textures, including:

  • Texture: A basic texture that can be applied to materials.
  • CanvasTexture: A texture generated from an HTML canvas element.
  • VideoTexture: A texture generated from a video element.
  • CubeTexture: A texture used for environment mapping, typically representing a panoramic image.
  • DataTexture: A texture generated from raw pixel data.

Textures can be mapped onto materials using UV coordinates, which define how the texture is wrapped around the object's surface.


3. Example: Applying Materials and Textures

Here's an example of applying a material with a texture to a 3D object:

// Load a texture image
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('textures/brick.jpg');

// Create a material with the texture
const material = new THREE.MeshStandardMaterial({ map: texture });

// Create a box geometry
const geometry = new THREE.BoxGeometry(1, 1, 1);

// Create a mesh with the geometry and material
const mesh = new THREE.Mesh(geometry, material);

// Add the mesh to the scene
scene.add(mesh);

In this example, we load a texture image of bricks using a TextureLoader. We then create a MeshStandardMaterial with the loaded texture and apply it to a box geometry. Finally, we add the mesh to the scene.

By combining materials and textures, you can create a wide range of visual effects and realistic surfaces in your Three.js scenes.

Comments