Download HDRI textures and use Three.js

One of the most exciting projects is adding HDRI backgrounds in Three js. HDRI images are captured in 360 degrees from scenes such as interiors of rooms or open environments such as gardens, jungles or mountains. You can create any of these images yourself, but that’s not the topic of this tutorial. Instead, we’ll take one of these images from the website and use orbit controls to allow the user to turn the object and see everything in 360 degrees. We can also add objects to the scene and give them color or increase their metallicity and reduce their roughness to become spherical mirrors.

Recommended: Use NSDT editor to quickly build programmable 3D scenes

1. Add background in Three.js

The possibilities are endless and there are so many things you can do. For example, you can create an interior design of an empty room by adding 3D models of different furniture, rugs, cushions, etc. This tutorial is the beginning of creating a virtual world where you can virtually build your dream home and view it from all different sides. As we’ve said in other Three js tutorials, once you start using Three js, the sky is the limit.

We’ll start with the simple elements of a three.js scene, including camera, renderer, scene, objects, and lights (if needed). Prior to this, we used the Vite plugin to easily create all the folders and files needed to run Three.js code. First, create a folder in the project directory using the following command:

mkdir BackgroundScene
cdBackgroundScene

Then, in the folder, run the Vite plugin command to create the necessary files and folders:

npm create vite@latest

Then, enter a project name. You can use glowingSphere as the name. However, the name is arbitrary and you can choose any name you want. Then, select vanilla as the framework and variant. After that, enter the following command in the terminal:

cd BackgroundScene
npm install

Next, you can enter the JavaScript code you want to write in the main.js file. Therefore, we will enter basic or template code for running each project with animated objects (such as spheres). Also, don’t forget to install the three.js package every time you create a project:

npm install three

Enter the following code in the main.js file:

import * as THREE from 'three';
import { Mesh } from 'three';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, innerWidth / innerHeight , 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
     antialias: true
})
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
//creating a sphere
const geometry = new THREE.SphereGeometry(5, 50, 50);
const material = new THREE.MeshBasicMaterial({
     color:0x3268F8
})
const sphere = new THREE.Mesh(geometry,material);
scene.add(sphere);
camera.position.z = 15;
function animate(){
     requestAnimationFrame(animate);
     renderer.render(scene,camera);
     sphere.rotation.y + = 0.003;
}
Animate();

The above code can serve as a template for subsequent projects. The output of this code will be a blue sphere as shown in the image below. However, to be able to display this, you should write the following command in the terminal:

pm run dev

2. Use the track control to set the background in Three.js

Now, we want to create a background scene to add, but before that we need to change the rendering from animation to orbit control so that we can control changing the scene from animation instead of rotating the object. Camera perspective. Doing this allows us to view HDRI images from all angles. First, we need to import the following 2 libraries:

import {OrbitControls} from "/node_modules/three/examples/jsm/controls/OrbitControls.js";
import Stats from "/node_modules/three/examples/jsm/libs/stats.module.js";

Then, all we have to do is modify the rendering code below:

function animate(){
     requestAnimationFrame(animate);
     renderer.render(scene,camera);
     sphere.rotation.y + = 0.003;
}
Animate();

The modified code looks like this:

const controls = new OrbitControls(camera, renderer.domElement);
window.addEventListener('resize', onWindowResize, false);
function onWindowResize() {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
      render();
}
const stats = Stats();
document.body.appendChild(stats.dom);
function animate() {
      requestAnimationFrame(animate);
      render();
      stats.update();
}
function render() {
      renderer.render(scene, camera);
}
animate();

Now we should be able to orbit the object. The next thing we should do is change the base material to a standard material and create a mirror effect:

const geometry = new THREE.SphereGeometry();
const material = new THREE.MeshStandardMaterial({
      color: 0xffffff,
})
material.roughness = 0;
material.metalness = 1;
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

3. Add HDRI environment map

Finally, we get to the most exciting part, which is adding the HDRI image to the background.

To do this, we need to first find these images from websites such as BimAnt HDRI. BimAnt HDRI provides more than 600 HDRI environment maps. The advantage is that they can be previewed and downloaded directly without logging in:

http://hdri.bimant.com

After that, we should create a folder called images and paste the HDRI images into it. Finally, add the following code to be able to render the background in the scene:

import {RGBELoader} from "/node_modules/three/examples/jsm/loaders/RGBELoader.js";
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 0.6;
renderer.outputEncoding = THREE.sRGBEncoding;
new RGBELoader().load("/images/solitude_4k.hdr", function(texture){
      texture.mapping = THREE.EquirectangularReflectionMapping;
      scene.background = texture;
      scene.environment = texture;
})

Now, if we save the code, the result will look like this:

When you click on the page with the left mouse button and move it left, right, up, or down, you’ll find that you can see the scene from all different angles. Additionally, since we defined the sphere material’s metallicity as 1 and roughness as 0, we can see a mirror effect on the sphere, reflecting the background scene in a realistic way.

It can be said that we don’t need any light source, but please note that if the object is close to the ground or in any other situation where the shadow of the ball needs to be seen, then it is necessary to add a light source to the scene and place it in a position where the light source ray is in the same direction as the sun ray .

4. Conclusion

In this tutorial, we have successfully added an HDRI environment map to the scene.

We started by using the Vite plugin and the boilerplate code we use in most Three js projects. We then removed the rotation animation and replaced it with orbit controls so that the user could use the mouse to view any angle of the scene they wanted.

The next thing we want to do is change the object’s material from the base material to the standard material so that we can add a mirror effect to the surface of the sphere. To achieve this, we set the metallicity to 1 and the roughness to 0

We then download the HDRI image from BimAnt HDRI and add it to our directory. Finally, we wrote a script related to adding background scenes and the results were amazing!

Of course, you can go through the same process with the interior design of the room and add some realistic furniture and other elements to the room background scene and create your own virtual reality version.

Original link: Three.js adds HDRI background – BimAnt