How to Repeat and Wrap Textures in Three.js
In Three.js, controlling how a texture maps onto a 3D surface is
essential for creating realistic materials. This article provides a
quick, direct guide on how to configure texture repeating and wrapping
behaviors using the wrapS, wrapT, and
repeat properties of the THREE.Texture
class.
Understanding Wrapping Modes
By default, Three.js textures do not repeat; they stretch the edge
pixels of the image if the texture coordinates exceed the 0 to 1 range.
To change this behavior, you must configure the wrapS
(horizontal/U direction) and wrapT (vertical/V direction)
properties of your texture.
Three.js offers three wrapping constants:
THREE.ClampToEdgeWrapping(Default): The texture coordinates are clamped to the 0.0 to 1.0 range, causing the edge pixels of the texture to stretch across the remaining surface of the mesh.THREE.RepeatWrapping: The texture repeats infinitely, tile-style.THREE.MirroredRepeatWrapping: The texture repeats infinitely, but mirrors the image with every iteration to create seamless transitions.
How to Set Repeat and Wrap Properties
To make a texture repeat, you must first define the wrapping behavior
on both axes to either RepeatWrapping or
MirroredRepeatWrapping, and then set the repeat frequency
using the repeat property.
Here is the direct code implementation:
import * as THREE from 'three';
// 1. Load the texture
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('path/to/your-texture.jpg');
// 2. Set the wrapping behavior for both horizontal (S) and vertical (T) axes
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
// 3. Define how many times the texture repeats along each axis
// texture.repeat.set(uRepeat, vRepeat)
texture.repeat.set(4, 4); // Repeats the texture 4 times horizontally and 4 times verticallyKey Considerations
- Power of Two Textures: Historically, WebGL required textures to have dimensions that were powers of two (e.g., 256x256, 512x512, 1024x1024) to support repeating. Modern WebGL 2 systems handle non-power-of-two (NPOT) textures seamlessly, but using power-of-two dimensions remains a best practice for performance and compatibility.
- Updating Textures: If you change the
wrapSorwrapTproperties after the texture has already been rendered by the GPU, you must settexture.needsUpdate = true;to force Three.js to upload the new configuration to the GPU.