Environment Map
Learn how to use an environment map to create reflections from objects in scenes in Three.js.
Fake reflections using an environment map
Calculating environment reflections is very CPU-intensive, and it usually requires a ray tracer approach. If we want to use reflections in Three.js, we can still do that, but we’ll have to fake it. We can do so by creating a texture of the environment the object is in and applying it to the specific object. First, we’ll show the result that we’re aiming for:
Example: Texture environment map
Let’s execute the texture-environment-map.js
example in the below playground by clicking the “Run” button:
const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') // const CopyWebpackPlugin = require('copy-webpack-plugin') const fs = require('fs').promises // we should search through the directories in examples, and use // the name from the files to generate the HtmlWebpackPlugin settings. module.exports = async () => { return { module: { rules: [ { test: /\.glsl$/i, use: 'raw-loader' } ] }, mode: 'development', entry: { 'chapter-10': './samples/chapters/chapter-10/texture-environment-map.js', }, output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/', }, plugins: [ new HtmlWebpackPlugin(), ], experiments: { asyncWebAssembly: true }, devServer: { allowedHosts: 'all', host: '0.0.0.0', port: '3000', static: [ { directory: path.join(__dirname, 'assets'), publicPath: '/assets' }, { directory: path.join(__dirname, 'dist') } ] }, mode: 'development', } }
Note: We can change the properties of the environment map from the right control panel in the output screen.
In the preceding screenshot, we can see that the sphere reflects the environment. If we move our mouse around, we will also see that the reflection corresponds with the camera angle, concerning the environment we see. To create this example, perform the following steps:
Lines 5–30: Create a
CubeTexture
object. ACubeTexture
is a set of six textures (like in lines 5–12) that can be applied to each side of a cube.Lines 86–91: Set the skybox. When we have a
CubeTexture
, we can set it as the background of the scene. If we do this, we effectively create a very large box, inside of which the cameras and objects are placed, so that when we move the camera around, the background of the scene also changes correctly. Alternatively, we could also ...