These elements are crucial for creating realistic and immersive 3D environments in Three.js. They help define the atmosphere, visual boundaries, and reflective properties of your scene.
Fog adds a sense of depth and distance to your scene by making objects appear less distinct as they get further away. Three.js provides two main types of fog:
THREE.Fog(color, near, far): Creates linear fog. The fog starts at near distance and becomes fully opaque at far distance.THREE.FogExp2(color, density): Creates exponential fog, where the density increases exponentially with distance. density controls how quickly the fog becomes opaque.To apply fog, you set the scene.fog property to an instance of either THREE.Fog or THREE.FogExp2. It's often recommended to set the scene.background color to the same color as the fog for a seamless transition, especially with linear fog.
// Linear Fog
scene.fog = new THREE.Fog(0xcce0ff, 10, 100); // light blue color, starts at 10 units, opaque at 100 units
// OR Exponential Fog
// scene.fog = new THREE.FogExp2(0xcce0ff, 0.01); // light blue color, density 0.01
The scene's background can be a solid color, a panoramic image, or an environment map. Setting a background helps to define the overall mood and context of your 3D world.
// Solid color background
scene.background = new THREE.Color(0x121212);
// Panoramic image background (using a texture loader)
// const textureLoader = new THREE.TextureLoader();
// textureLoader.load('path/to/your/panorama.jpg', function(texture) {
// scene.background = texture;
// });
Environment maps are images that surround the scene and can be used for reflections and lighting on objects, as well as for the background. They are particularly effective with physically based rendering (PBR) materials like MeshStandardMaterial and MeshPhysicalMaterial to create realistic reflections.
You can load cube textures (six images for the faces of a cube) or equirectangular textures (a single panoramic image) and set them as scene.environment (for reflections) and/or scene.background.
// Example using an equirectangular HDR environment map
// import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
// const pmremGenerator = new THREE.PMREMGenerator(renderer);
// pmremGenerator.compileEquirectangularShader();
// new RGBELoader()
// .setPath('path/to/your/environment/maps/')
// .load('your_environment_map.hdr', (texture) => {
// const envMap = pmremGenerator.fromEquirectangular(texture).texture;
// texture.dispose();
// scene.environment = envMap; // For reflections on PBR materials
// scene.background = envMap; // Set as background
// // Optional: Add blur to the background
// scene.backgroundBlurriness = 0.5; // Value between 0 and 1
// });
This example demonstrates a simple scene with fog and a matching background color, creating a sense of atmospheric depth.