...

/

Textures in Materials

Textures in Materials

Learn how to load basic textures and use them in the materials in Three.js.

Let’s start with a basic example, where we will show how to load and apply a texture.

Using textures in materials

There are different ways that textures can be used in Three.js. We can use them to define the colors of the mesh, but we can also use them to define shininess, bumps, and reflections. The first example we will look at, though, is very basic, wherein we will use a texture to define the colors of the individual pixels of a mesh. This is often called a color map or a diffuse map.

Loading a texture and applying it to a mesh

The most basic usage of a texture is when it’s set as a map on a material. When we use this material to create a mesh, the mesh will be colored based on the supplied texture. Loading a texture and using it on a mesh can be done in the following manner:

Press + to interact
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('/assets/textures/ground/ground_0036_color_1k.jpg')

In this code sample, we are using an instance of THREE.TextureLoader (line 1) to load an image file (line 2) from a specific location. Using this loader, we can use PNG, GIF, or JPEG images as input for a texture. Note that textures are loaded asynchronously: if it is a large texture and we render the scene before the texture is completely loaded, we’ll see our meshes without a texture applied for a short time. If we want to wait until a texture has been loaded, we can provide a callback to the textureLoader.load() function:

Press + to interact
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('/assets/textures/ground/ground_0036_color_1k.jpg',
onLoadFunction,
onProgressFunction,
onErrorFunction)

As we can see, the load function takes three additional functions as parameters: onLoadFunction is called when the texture is loaded (line 3), onProgressFunction can be used to track how much of the texture is loaded (line 4), and onErrorFunction is called when something goes wrong while loading or parsing the texture (line 5). Now that the texture has ...