Create a Three.js Skybox Using CubeTexture

This article explains how to use a CubeTexture in Three.js to create an immersive 3D background known as a skybox. You will learn what a CubeTexture is, the specific order required for loading its six face images, and the exact code needed to implement a seamless environment map in your Three.js scene.

What is a CubeTexture?

In Three.js, a CubeTexture is a special type of texture composed of six individual images mapped onto the inside faces of a cube. Instead of projecting a single flat image, a cube texture wraps around the entire camera viewpoint, creating a seamless 360-degree environment. This technique is commonly used to render distant backgrounds (skyboxes) and to calculate realistic reflections and refractions on 3D objects.

How to Load Six Images to Create a Skybox

To create a skybox, you use the CubeTextureLoader class. This loader requires six distinct image files, each representing one side of the cube.

1. The Correct Image Order

Three.js expects the six images to be defined in a specific order representing the axes of a 3D coordinate system. The correct array order is:

  1. px (Positive X / Right)
  2. nx (Negative X / Left)
  3. py (Positive Y / Top)
  4. ny (Negative Y / Bottom)
  5. pz (Positive Z / Front)
  6. nz (Negative Z / Back)

2. Loading the Texture and Applying it to the Scene

To apply the skybox to your scene, instantiate a CubeTextureLoader, load the images, and assign the resulting texture to your scene’s background property.

Here is the complete code implementation:

import * as THREE from 'three';

// 1. Create your Scene
const scene = new THREE.Scene();

// 2. Initialize the CubeTextureLoader
const loader = new THREE.CubeTextureLoader();

// 3. Load the six images in the correct order
const texture = loader.load([
    'path/to/px.jpg', // Right
    'path/to/nx.jpg', // Left
    'path/to/py.jpg', // Top
    'path/to/ny.jpg', // Bottom
    'path/to/pz.jpg', // Front
    'path/to/nz.jpg'  // Back
]);

// 4. Set the texture as the scene background
scene.background = texture;

Once applied, the renderer automatically projects these six images onto an infinite boundary around the camera. As your camera rotates, the background rotates accordingly, producing a realistic sense of depth and scale.