Blog>
Snippets

Creating a Skybox with CubeTextureLoader

Use the CubeTextureLoader to add a skybox to the scene, creating an immersive background environment.
// Step 1: Import necessary Three.js components
import * as THREE from 'three';

// Step 2: Set up 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);
Import THREE.js components, then create the scene, camera, and renderer and add the renderer to the document.
// Step 3: Create the CubeTextureLoader
const loader = new THREE.CubeTextureLoader();

// Step 4: Set the path to the images
loader.setPath('textures/skybox/');
Instantiate a CubeTextureLoader and set the path to where the skybox textures are located.
// Step 5: Load the textures for each side of the skybox
const textureCube = loader.load([
  'px.jpg', 'nx.jpg',
  'py.jpg', 'ny.jpg',
  'pz.jpg', 'nz.jpg'
]);
Load the six textures for the skybox, representing the positive x, negative x, positive y, negative y, positive z, and negative z faces of the cube.
// Step 6: Add the skybox Background
scene.background = textureCube;
Set the loaded textures as the background of the scene, creating a surrounding skybox effect.
// Step 7: Animate the Scene
function animate() {
  requestAnimationFrame(animate);

  // Update other elements like camera or objects inside the scene if necessary

  // Render the scene
  renderer.render(scene, camera);
}

animate();
Define the animation loop, which allows the scene, including the skybox, to be rendered continuously. Any additional updates to the scene during the animation loop would also be placed here.