Subscribe to our free newsletter

To make sure you won't miss any valuable content we share with our community.

How to Use Perspective Camera in Three JS

One of the things that many new learners have difficulty with is about the perspective camera in Three js. Like our previous articles about Three js lights and others, we are going to cover a very problematic concept in Three js. This is something that may cause misunderstanding. So, we need to get into it deeply.

Perspective and Other Cameras in Three JS

In general, Three js is a library that allows you to visualize the 3D data in the form of meshes and lights. Then, convert that data into a 2D representation for an HTLM canvas. However, a Three js scene does not boil down to meshes and lights. There are 3 main elements before starting to add any item. These elements are the camera, the scene, and the renderer.

The renderer displays the scene onto an HTML canvas element and uses WebGL by default. The scene, which is created at the beginning of every project, allows you to set up what is to be rendered by Three js and the coordinates of the items. And at last, we have a camera. There are 2 types of cameras in general considering the way they see the object including the Perspective camera and the Orthographic camera. However, there are other types of cameras used in Three js such as array camera, Cube camera, and the Stereo camera. Throughout this article, we will introduce cameras in detail and provide examples for the perspective camera.

Perspective vs Orthographic in Three JS

The perspective camera and the orthographic one are most usually compared due to the differences they have in the perspective view. The perspective camera mimics the way the human eye sees objects whereas the orthographic camera is like a cube in itself where the perspective remains constant as the object gets further meaning that the size remains the same regardless of the distance of the camera from the object.

The 2 photos below show exactly how the perspective camera differs from the orthographic one. The first photo represents the view from the perspective camera, as you can see, as the view plane gets further from the camera (eye point), the space that the camera viewport can cover, gets larger. While, if you look at the second photo, the size of the object won’t change as it gets further from the viewpoint.

Stereo Camera’s Role in Using Perspective in Three JS

The stereo camera uses dual perspective cameras for effects like 3D anaglyph or parallax barrier. The 3D anaglyph in summary is a kind of effect that creates the perception of a 3-dimensional photo by providing 2 layers of filtered images of opposite colors like red and cyan. The 2 layers of images will be perceived as 3D using certain glasses that have 2 different filters on each glass which is going to reveal only one of the 2 layers for any of them. For instance, the left glass which is red filters one of the 2 layers, and the right one which is cyan will reveal the other layer.

The superposition of the layers filtered with certain glasses will result in the 3-dimensional perception. The stereo camera provides the kind of 3D scene that if the viewer wears the 3D glass will be able to see a 3-dimensional view on the screen. In the following photo, you can see an anaglyph photo. On the other hand, the parallax barrier provides a kind of 3d image perception without the need for the viewer to wear 3D glasses.

Cube Camera

Is a kind of camera that creates 6 cameras that render to a WebGL Cube Render Target. One of the examples shown by the Three js official website is a rotating view over a sphere. The type of camera that is used for the 6 cameras is the perspective type.

Array Camera

Array camera is normally used in VR scenes where a set of cameras are considered to efficiently cover all the viewports. In other words, as we need different cameras to cover different views in VR scenes, an array of cameras are considered to cover a specified part of the 3D scene. The kind of camera that is used for each sub camera, is the perspective type.

Basics of Using Perspective Camera in Three JS

We are going to get started with the simple elements of a Three js scene including the camera, the renderer, the scene, the object, and the light source (if necessary). Before we do that, we’d rather use the Vite plugin to be able to easily create all the folders and files that you need to run the Three.js code. First off, create a folder in the directory of your projects by using the following commands: mkdir Camera
cd camera
Then, inside of the glowing sphere folder, create the necessary files and folders by simply running the Vite plugin command: npm create [email protected] Then, enter the name of the project. You can write glowingSphere as the name. And also the package (the name is arbitrary and you can choose anything that you want). Then select vanilla as the framework and variant. After that, enter the following commands in the terminal: cd camera
npm install
Then, you can enter the javascript code that you want to write in the main.js file. So, we will enter the base or template code for running every project with an animating object, such as an sphere. Also do not forget to install Three js package library every time create a project: npm install three Now, enter the following script 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 be used as a boilerplate for later projects. The output of this code will be blue sphere like the following photo. But to be able to show that, you should write the following command in the terminal: npm run dev

Now, we want to change the result in order to test the perspective camera with the wireframe of a cube. So change:

const material = new THREE.MeshBasicMaterial({
     color:0x3268F8
})


To:

const geometry = new THREE.BoxGeometry(8, 8, 8);
const material = new THREE.MeshStandardMaterial();
material.color = new THREE.Color(0xB1E1FF);
material.roughness = 0.2;
material.metalness = 0.7;
material.wireframe = true;


Also, add an ambient light to the scene so that you can see the wireframe made with the standard mesh material:

const light = new THREE.AmbientLight( 0xffffff); 
scene.add(light);


Save the code and you will be able to see a result like this in your browser:

The above result is the representation of the perspective camera. If we change the camera to orthographic by writing:

const camera = new THREE.OrthographicCamera( innerWidth / -14, innerWidth / 14, innerHeight / 14,
     innerHeight / - 14, 1, 100 );


The result will be:

Summing Up

In this article, we have got familiar with the concept of the camera in Three js and got familiar with different types of it. Furthermore, we compared the 2 main camera views including the perspective and the orthographic view. Not only that, but we also wrote some Three js scripts to see the differences between the orthographic camera and the perspective one when viewing the wireframes of a cube (box geometry). Moreover, we introduced different cameras from the number of cameras used to view a certain space. These types of cameras were stereo camera, cube camera, and array camera.

Download this Article in PDF format

three js

Curious about What We’re Up To?

In Arashtad we provide custom services in various design and development fields. 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications are just some of our expertise.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Request a Quote
Blockchain Development

Creating Glowing Sphere in Three JS + Notable Hints

One of the very useful projects that can be used for larger projects is creating a glowing sphere using Three js. The use cases of this object are very wide. It can be used for simulating the sun, the moon, the planets, or the planet earth itself. A glowing sphere usually has a kind of halo based on the kind of object it is. For instance, the planet earth needs a kind of a halo for simulating its atmosphere or the moon needs a halo for simulating the white light around it. When we want to simulate the sun in open space, we need a glowing sphere as well.

Creating a Glowing Sphere from Scratch

In this article, we are going to get familiar with the steps we can take to create a glowing sphere in Three js. Of course, we are going to simulate the halo of the glowing sphere with the aid of shaders. If you are a beginner, don’t worry because we are going to teach you how to do this task from scratch.

As we mentioned earlier, a glowing sphere is composed of the sphere itself with a halo which we are going to design using a shader. There is also another important element that we should consider when designing a glowing sphere and that is considering a light source for it. The position of the light source should be the same as the position of the object. As a result, the object will work as a light source as well.

Basics of Creating Sphere in Three JS

We are going to get started with the simple elements of a Three js scene including the camera, the renderer, the scene, the object, and the light source (if necessary). Before we do that, we’d rather use the Vite plugin to be able to easily create all the folders and files that you need to run the Three.js code. First off, create a folder in the directory of your projects by using the following commands: mkdir glowingSphere
cd glowingSphere
Then, inside of the glowing sphere folder, create the necessary files and folders by simply running the Vite plugin command: npm create [email protected] Then enter the name of the project. You can write glowingSphere as the name. And also the package (the name is arbitrary and you can choose anything that you want). Then select vanilla as the framework and variant. After that, enter the following commands in the terminal: cd glowingSphere
npm install
Afterward, you can enter the javascript code that you want to write in the main.js file. So, we will enter the base or template code for running every project with an animating object, such as an sphere. Also do not forget to install Three js package library every time create a project: npm install three Now, enter the following script 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 be used as a boilerplate for later projects. The output of this code will be blue sphere like the below photo. But to be able to show that, you should write the following command in the terminal: npm run dev

glowing sphere

Creating A Glowing Sphere

Now, if we want to create a halo to make it glow, we need to create a shader. So, we modify the code a bit. To do so, add the followings to the main.js:

const haloVertexShader = /*glsl*/`
varying vec3 vertexNormal;
void main() {
     vertexNormal = normal;
     gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);   
}
`;
const haloFragmentShader = /*glsl*/`
varying vec3 vertexNormal;
void main() {
float intensity = pow(0.9 - dot(vertexNormal, vec3(0, 0, 1.0)), 2.0);
gl_FragColor = vec4(0.8, 1.0, 0.6, 0.2) * intensity;
}
`;
const halo = new THREE.Mesh(
     new THREE.SphereGeometry(5, 50, 50),
     new THREE.ShaderMaterial({
          vertexShader:haloVertexShader,
          fragmentShader:haloFragmentShader,
          blending: THREE.AdditiveBlending,
          side: THREE.BackSide
     })
)

scene.add(sphere);
halo.scale.set(1.2, 1.2, 1.2);
scene.add(halo);


Now, we save the code and see a halo around the sphere as a result:

glowing sphere

What we did here was to create a halo sphere using shaders. Shaders are usually written in other files called vertex.glsl and fragment.glsl. But here for the ease of code execution, we have written it in the main.js file with ‘ ‘ marks. Notice that you need to install the Comment tagged templates in VSCode to be able to support other languages in the main.js. This way writing shader is much easier and faster. In the haloFragmentShader, we have written an algorithm to create this kind of glowing effect and notice that we created another sphere in addition to the main sphere in the boilerplate to simulate a halo so that we can have the glowing sphere using the 2 of them in the same place. Adding the Texture of the Moon: In order to give meaning to our design, we can add the texture of the moon. To do so, we need the UV map of its surface. You can google UV map of the moon and the photo you need should be something like this:

moon texture

Now, we need to create a folder and paste the uv map of the moon and change the material from:

const material = new THREE.MeshBasicMaterial({
     color:0x3268F8
})


To:

const material = new THREE.MeshBasicMaterial({
     map : new THREE.TextureLoader().load('./img/moon.jpg')
})


What we actually did was to change the color property to the map property. Finally, you will be to see the rotating moon like this:

glowing sphere in three js moon example

The final thing that we need to do is to create a light point. We have covered a full tutorial on the point lights in our previous articles. We can use either the spotlight or the directional light to simulate the light in space. However, since we do not have any other objects here, we can neglect this part and do not add any light sources in the position of the moon. But if we want to have more objects and planets in space or simulate the moonlight in the night sky, we would rather use a spotlight or directional light.

Notice that if the planets are going to be simulated near each other, the spotlight might be a better choice. But if you want to simulate only the moon in the sky, the directional light may be a better option to provide the scene of a glowing sphere in the middle of the night, because we usually use the directional lights for the sources that are far away and have parallel beams. According to the above explanations, we use the directional light and consider the white color for it and then add it to the scene:

const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
scene.add( directionalLight );


Notice that you should set the position of the point light according to the sphere object (They should have the same position).

Final Word

In this tutorial, we have provided the guidelines for creating a sphere from scratch using the Vite plugin and the base code or boilerplate for every Three js project. Afterward, we added the fragment and vertex shaders written in GLSL to our script to simulate the glowing effect on our glowing sphere in Three js. The halo or the glowing effect comes from another sphere that has been scaled relative to the main sphere. Then, to give meaning to the glowing sphere we have created, we decided to create a moon with a UV map of it, which was downloaded from Google images. Finally, we considered adding a light source in case additional objects might be added to the scene in the future.

Download this Article in PDF format

metaverse

Curious about What We’re Up To?

In Arashtad we provide custom services in various design and development fields. 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications are just some of our expertise.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Request a Quote
3D Development

Three JS Lights: Create A More Realistic Design

Lighting is an important subject in every design process. With a perfect selection of light, you can create a more realistic view and a more natural one. For instance, the kind of light you use to create the scene of planet earth is totally different from the light you use to visualize an animal in the open air of sunny weather. There are many kinds of lights that can be used in Three js. These lights include ambient light, spotlight, spotlight, hemisphere light, point light, Rect area light, and directional light.

The Settings ofThree js Lights

In this article, we will cover all kinds of lights that can be used for all the different settings. We apply these light sources to a simple object with simple geometry. However, you can import your GLTF 3D model in Three JS and test each one of them with the specific lights that we present and see which one is the proper light source and what preferences are the best for each one of them. As mentioned earlier, there are many light sources available in Three js for most if not all of the objects that we want to visualize. These light sources have some attributes and settings that you can choose to make your lighting the right one for the scene. The most common is color. For example, you want to create a light source for an object under the blue sky. So you need the ambient light source with the color sky blue. Or in another example, if you want to visualize a planet in space with a yellow light source like the sun, you can use a spotlight or point light with yellow color.

Getting Started with a Simple Project

First off, make sure you have npm installed. You can start your first project by git cloning one of the simple Three.js projects to find a boilerplate for further development. Most of these projects can be found on Github, animate simple objects like a cube, sphere, torus, and so on. The animation is usually rotation. Running these projects and developing them step by step by changing some of the features about rendering, lighting, camera perspective, the color of the objects, textures, animations, and so on will help you find the necessary tools to design more complex objects.

We start our first project by git cloning one of the Github repositories. To do so, enter the following command in the terminal: mkdir Starting_Three
cd Starting_Three
git clone https://github.com/designcourse/threejs-webpack-starter
Then, enter the following commands one by one to install the dependencies: npm install
npm install webpack-dev-server -g
Now change the directory to threejs-webpack-starter: cd threejs-webpack-starter Then enter the followings one by one to get a pre-designed 3D animated torus: pm i
npm run dev
npm run build
And you will be able to see the animated (rotating) torus like this in your browser:

Now, let’s head over to our JavaScript code behind the scenes and see the elements of this 3D design and rendering. In src folder, script.js file, you will use some scripts that we are going to modify later.

Three JS Point Lights

A point light is a kind of that gets emitted from a single light source in all directions. A simple example of a point light is a light bulb in a room. The point light constructor is composed of 4 elements including the color, the intensity which is the numeric value of the light’s strength and by default is set to 1, and the distance which is the maximum range of the light that is by default set to 0. The decay which is the amount that the light dims along the distance from the light and by default is set to 1 and you can set it to 2 if you want a more natural result. Now, it is time to put the function to test, but before we do that, let’s modify the raw code a little bit. First of all instead of a simple torus as the geometry, create a Torus Knot :

const geometry = new THREE.TorusKnotGeometry( 0.5, 0.15, 100, 64 );


Second of all, we can change the material from basic to standard by writing:

const material = new THREE.MeshStandardMaterial();


Instead of:

const material = new THREE.MeshBasicMaterial();


And then, we can apply the metalness , roughness and color effects:

material.metalness = 0.7;
material.roughness = 0.2;
material.color = new THREE.Color(0xB1E1FF);


The next thing that we should do is to modify the renderer a little bit from:

const renderer = new THREE.WebGLRenderer({
 canvas: canvas
})


To:

const renderer = new THREE.WebGLRenderer({
 canvas: canvas,
 alpha: true
})

And finally, we can apply the point light by writing:

const pointLight = new THREE.PointLight(0xffffff, 0.1);
pointLight.position.x = 2;
pointLight.position.y = 3;
pointLight.position.z = 4;
pointLight.intensity = 2;
scene.add(pointLight);

Now, save the code and the result will be:

Three JS Ambient Lights

Ambient light is a kind of light that globally illuminates all objects equally. Since the ambient light has no direction at all, it cannot cast shadows. The function has attributes, the first of which is color and the second is intensity. Notice that if you use MeshBasicMaterial instead of MeshStandardMaterial, the object will have the ambient light when any kind of light is used like the one you saw when running the very first raw code. But for the case of MeshStandardMaterial, if you want to get the same result, you should use the ambient light.

Now, let’s comment the light point scripts and add the ambient light instead:

const light = new THREE.AmbientLight( 0xB1E1FF,2 );
scene.add( light );


By saving the code, the result will be:

Three JS Hemisphere Lights

Hemisphere light is a kind of light source placed directly above the scene and the color and intensity fades from the sky to the ground. Like the ambient light, this light source cannot be used to cast shadows either. The attributes of this type of light source is sky color, ground color and the intensity of the light. By commenting the ambient light codes, copy and paste the below code to test the Hemisphere light source:

const skyColor = 0xB1E1FF; 
const groundColor = 0xB97A20; 
const intensity = 2;
const light2 = new THREE.HemisphereLight(skyColor, groundColor, intensity);
scene.add(light2);

And you can see the result below:

Three JS Rect Area Lights

Rect area light emits light uniformly across the face of a rectangular plane, simulating the light coming from a window or a screen. Although we have shadows on the object in the scene, there is no shadow supported in this type of light source. And Only MeshStandardMaterial and MeshPhysicalMaterial are supported by Rect area light. The attributes of the corresponding function are color, intensity, and width which is the width of the window and is set to 10 by default, and the height of the window which is also set to 10 by default.

Let’s replace the previous light source with the new one using the script below:

const width = 20;
const height = 20;
const intensity = 5;
const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
rectLight.position.set( 5, 5, 5 );
rectLight.lookAt( 0.5, 0.5, 0.5 );
scene.add( rectLight );

Three JS Directional Lights

Directional light represents the kind of light from a very far away light source like the sun with parallel beams. This type of light source supports shadow casting. The light also emits in one direction like daylight. The attributes used for the corresponding function are simply the color and the intensity. It is worth mentioning that you can use this type of light to simulate the planet earth.

Now, let’s replace the following script with the previous one and see the outcome:

const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
scene.add( directionalLight );


Spotlight Features

The last type of light we are going to cover in this article is the spotlight source. This light is so similar to the directional light and gets emitted from a single point in one direction, along a cone that increases in size the further from the light it gets. This type of light supports shadow casting. The spotlight function has 7 attributes including the color, the intensity, the distance, angle, penumbra which is the percent of the spotlight cone that is attenuated due to penumbra and takes a value between zero and one and the last parameter is decay which is The amount the light dims along the distance of the light.

Let’s test this type of light by replacing the following scripts with the previous one:

const spotLight = new THREE.SpotLight( 0xffffff );
spotLight.position.set( 10, 10, 10 );
spotLight.castShadow = true;
spotLight.shadow.mapSize.width = 24;
spotLight.shadow.mapSize.height = 24;
spotLight.shadow.camera.near = 50;
spotLight.shadow.camera.far = 40;
spotLight.shadow.camera.fov = 3;
scene.add( spotLight );

Wrapping Up

In this article, we have introduced all the different light sources that you can use in Three js with their corresponding details. Moreover, we have provided some simple examples for each one of them so that the reader can put all of the light sources to test and find the appropriate type of light for their own scene. In addition to that, we have addressed a simple boilerplate for Three js so that the beginners can start using this plate and develop it with the light sources that we introduce along the way.

Download this Article in PDF format

metaverse

Curious about What We’re Up To?

In Arashtad we provide custom services in various design and development fields. 3D websites, 3D games, metaverses, and other types of WebGL and 3D applications are just some of our expertise.

Arashtad Serivces
Drop us a message and tell us about your ideas.
Request a Quote
3D Development