blog image
Blog Articles

Three.js ! Another Js library but why ?    

Introduction

Three. js is an open-source, lightweight, cross-browser, general-purpose 

JavaScript library. Three. js uses WebGL behind the scenes, so  we can use it to  render Graphics on an HTML <canvas> element in the browser.       
It helps us to create and display animated, GPU-accelerated 3D graphics in web browser with use of WebGL. Three.js makes it easier to do that than using a low-level API of WebGL, that requires extensive knowledge. And with a use of it we can do almost everything that we can imagine.                                                           

Quick overlook:

We need to install the Three.js library using npm (or yarn if you prefer). In the console              we need to use the following command:

npm install three

Lastly, we need to start development server to see all the changes that we’re doing in the browser. To make it quick we can use bundler called Parcel. To run index.html file using Parcel we need to use following command:

npx parcel index.html 

Some important methods:

1. Scene – box for everything else

To better understand how Three.js works we can think of our scene like a movie plan. The scene object is our plan. On it, we can put our objects, which also exists in Three library – camera, lights, meshes (actors) and so on.
to create a scene we’ll use:

const scene = new THREE.Scene()

2. Camera – our eyes in 3D world

Right now, we don’t know yet what is happening on the scene, because we can’t look inside of it. So first, we need to put a camera in it, which will work as our eyes inside the scene. In Three.js we have multiple cameras to choose from, but the most used ones are:
Orthographic camera – used mostly for flat, 2D scenes, as it doesn’t take perspective into account,Perspective camera – used for rendering 3D scenes, taking perspective into account, working almost like a human eye.

We’ll create our camera using the following parameters and then add it to the scene, as every object should be:

const aspect = window.innerWidth / window.innerHeight
const camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 100)
scene.add(camera)

The perspective camera constructor takes 4 arguments, and it’s very important to know and understand all of them:

  • FOV (field of view) – it’s the angle between top and bottom plane of camera frustum view,
  • Aspect ratio – ratio of the visible scene (typically ratio of canvas width to canvas height),
  • Near – the distance from camera to the plane from which the camera “can see”,
  • Far – the distance from the camera to the plane from which the camera “can’t see”.

3. Renderer – the brain of all operations

Once we have a camera on our scene, we can finally render it. For that, we’ll use object called renderer. Its job is to analyze everything on the scene – positions of objects in relation to another objects, to the world coordinates etc. and display it on our canvas, taking all this properties into account.
Let’s create it:

const renderer = new THREE.WebGLRenderer({ canvas, antialias: true })
renderer,setClearColor(0x222222)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setPixelRatio(window.devicePixelRatio)

Then, we need to use render method of renderer to display the scene. It takes two arguments: the scene which will be rendered, and the camera that will be used to render it. So basically it’s like saying: “Hey renderer! Use the image of my scene from this camera and display it on the canvas”.

renderer.render(scene, camera)

4. Box – so we can see something

Geometry – shape it

Geometry is like a skeleton, a shape of an object (created from vertices, edges and faces). We can use geometries included in the Three.js library (plane, box, sphere and others) or they can be custom made. You can see all geometries offered by Three.js in its documentation, where you can find a sandbox for every geometry, control all parameters and see how they change the shape of geometry, so I highly recommend to try it.

Material – dress it up

The other element that builds the mesh is material. It’s like a skin of a geometry and it determines how the object will look on the scene, how it will interact with the lights and so on. Materials have many parameters and every one of them is different, so you can check it in the documentation. With material we can use textures, height maps, normal maps and many other.

Mesh – let’s put it together

As our object we will use the BoxGeometry, which as you can see in the documentation takes six arguments: width, height, depth, and the number of segments for width, height and depth. We’ll use only first three of them and leave the rest as default.

const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 0x781CE5 })
const mesh = new THREE.Mesh(geometry, material)
scene.add(mesh)


Ok, we have our actor on the scene, but it’s still empty. What is happening here? The answer is simple. Let’s remember that we are in a 3D space with x, y and z axis, so it looks something like this:



By default, every element added to the scene have the following coordinates: x = 0, y = 0 and z = 0. Right now our camera and object are in the same place of a scene, so we are „filming” our scene from inside of our cube! 

The conclusion is simple, we need to move something, either camera or object. We’ll move camera on Z axis so it’s away from the cube. Add this line below the camera constructor and above adding the camera to the scene:

camera.position.z = 2

We have our object! But it’s flat… That’s because we are looking forward at it. Let’s move the camera on other axis and make it look at the point where the cube is, so the center of the scene (0,0,0). Change the previously written line of code to the following:

camera.position.set(2, 2, 2)
camera.lookAt(0,0,0)

5. Lights – light up your scene


There are a lot of lights in Three.js and you can refer to documentation to know all of them. We add them to the scene like any other objects, but their configuration is different thing, so it’s really a matter of experimenting with their properties. 

For our example we will use two lights:

  • ambient light – a light that illuminates objects equally from all sides,
  • point light – we need to position it somewhere in 3D space and it illuminates in all directions from this point, acting like a bulb.

To use lights, first, we’ll need to change the material of an object to the one that reacts with the light, so let’s change it to standard material:

const material = new THREE.MeshStandardMaterial({ color: 0x781CE5 })

Then, we can add lights.

const ambient = new THREE.AmbientLight(0x404040, 5)
const point = new THREE.PointLight(0xE4FF00, 1, 10)
point.position.set(3, 3, 2)
scene.add(ambient)
scene.add(point)

6. Let’s Add Some Animation

Right now, we’re rendering our scene only once – when we use render method of a renderer. We’d like to make our cube spin, so we must render our scene multiple times, every time adding some value to the rotation of the cube.
Luckily, we have the function that is created exactly for this and it’s available on the window object. It’s called requestAnimationFrame and it can be used to call animation function ideally in 60 frames per second (generally matching the display refresh rate). This function as an argument takes callback function that should be called before the next repaint.
Ok, so to use it we’ll create a function called animate that will call render method and will be called recursively using requestAnimationFrame. That way we will call render method multiple times in a second. Also, in every frame (every time the function is called) we’ll change the rotation of a cube a little, so at the end we will have a smooth, rotating cube.

function animate() {
mesh.rotation.x += 0.003
mesh.rotation.y += 0.004
mesh.rotation.z += 0.005
renderer.render(scene, camera)
window.requestAnimationFrame(animate)
}
animate()

*
To get an idea of what would it result into click on this link : LINK

Conclusion:

Hope this small but insightful example gives a bite of what threeJs is all about, in the beginning, like any library, getting used to might be a bit daunting but the agility of this technology to add animation to our application relieves the pain taken by the developer to master this amazing library.

Sign Up Now
Get a Fast Estimate on Your Software Development Project

We are committed to delivering high-quality IT solutions tailored to meet the unique needs of our clients. As part of our commitment to transparency and excellence, we provide detailed project estimations to help our clients understand the scope, timeline, and budget associated with their IT initiatives.

Related Post

The Power of Rich Text Editing with jodit-react

Introduction Rich text editors have become an inseparable part of the web development services world now and every platform has to ensure that software development companies and users have an…

View Article
Ace Editor Mastery: Enhancing Your Code Editing Skills with React

Among website development and mobile application development, A code editor can increase the code editing efficiency and the working conduct, finally leading to program structure perfection, workflow optimization and development…

View Article
Zustand: A Lightweight State Management Library for React

One of the most essential things when it comes to creating modern web applications, particularly projects in React, is state management. Whilst the built-in state management hooks of React such…

View Article
Smartlook Integration in Ionic App

Introduction When it comes to mobile apps, a smooth and intuitive user experience is absolutely necessary in the current competitive mobile app market. App developers should not forget about user…

View Article
FCM Legacy to HTTP v1 Migration with APEX: Developer’s Handbook

Introduction FCM, or Firebase Cloud Messaging, has always been a leading choice for reaching your users with notifications and messages regardless of the platform. Nevertheless, the technology is not limited to…

View Article
Your Ultimate Guide to Hiring the Best React Native Developers 

In this digitalized age, finding the best react native developers for hire becomes an indispensable need of a business. First and foremost, the project-specific needs identification ensures a good hiring…

View Article