Set Equirectangular Background in Three.js

This article explains how to apply a 360-degree equirectangular texture directly to a Three.js scene background. By utilizing the built-in mapping properties of Three.js, you can easily create an immersive panoramic environment without the need for large, custom sphere geometries.

To apply an equirectangular texture to your scene background, you must load the image using a texture loader and set its mapping type to THREE.EquirectangularReflectionMapping. This tells Three.js to project the 2D spherical image correctly onto the infinite background of the 3D scene.

Here is the step-by-step implementation:

1. Load the Texture

Use THREE.TextureLoader for standard image formats like JPG or PNG. If you are using High Dynamic Range (HDR) images, you should use RGBELoader instead.

2. Configure the Mapping

Set the loaded texture’s mapping property to THREE.EquirectangularReflectionMapping. This is the crucial step that transforms the flat image into a 360-degree projection.

3. Assign to the Scene Background

Assign the configured texture directly to scene.background. You can also assign it to scene.environment to automatically illuminate physical materials in your scene with the background’s light.

Code Example

import * as THREE from 'three';

// Create the scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

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

// Load the equirectangular image
loader.load('path/to/your/panorama.jpg', function (texture) {
    // Set the mapping to equirectangular
    texture.mapping = THREE.EquirectangularReflectionMapping;
    
    // Assign the texture to the scene background
    scene.background = texture;
    
    // Optional: Assign to environment for realistic reflections on objects
    scene.environment = texture;
});

// Position the camera inside the background
camera.position.set(0, 0, 0.1);

// Animation loop
function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}
animate();

Color Space Consideration

When loading standard images (like PNG or JPG) as backgrounds, ensure your renderer’s color output matches the texture. For modern Three.js versions, set the texture color space to match your setup:

texture.colorSpace = THREE.SRGBColorSpace;