Explore the Virtual World of Three.js

Gurpreet Singh
tech@iiit-gwalior
Published in
7 min readDec 8, 2021

Hello Fellas,
Yeah, I know, such a cheesy title. But stay for a bit, and you’ll realize what I meant. So, the story began a few days back when I was having my coffee and was chilling watching a video where some geeky-looking guys were trying to recreate the famous Trench run scene from Star Wars 6: A New Hope using VFX and Blender. Me being a developer, started wondering “ Hmm…, all this is cool and stuff, but wouldn’t it be amazing if I could add such a 3D model to my website”. So, what I did next, you guessed it right, I googled it ;). And the answer to my question was Three.js

So, what is Three.js?

According to Google,
Three.js is a cross-browser JavaScript library and application programming interface used to create and display animated 3D computer graphics in a web browser using WebGL.”

In short, it’s an amazing library where you can play with 3D models and WebGL, a Javascript API, which helps you to render your 2D or 3D models on your browser itself.

This much description is not enough for you, so let’s create a simple model which will give you a glimpse of what Three.js can do?

Setting up the development environment

Without further ado let’s head to VS code (no offense to other IDE users, but you need an upgrade 😉). We’ll be hosting our static files through Vite, which is a build tool that enhances the development environment of any frontend framework. In terminal type,

$ npm init vite@latest
// or
$ yarn create vite

After this, you’ll be prompted to select a framework with which you want to integrate through Vite, just select Vanilla from the options as it is not a React session.

After it gets downloaded, your folder structure will look like this :

Now run npm install three to install Three.js as a dependency. Now we are ready to rock n’ roll.

Setting up the stage for our play :)

If you have ever watched behind the scenes of any movie or a play, you might know that the director needs to set up a whole lot of things for any scene. We’ll be doing something similar here. So, LIGHTS, CAMERA, ACTION!!

Creating a scene

Let’s create a scene for our play 😌. First and for most import Three.js from the library we just imported in the main.js file. Then create a scene just like this :

Yeah, it’s an image, but don’t worry about the whole code, it has been provided at the end of this article ;)

What do you mean by “That’s sit?”, There’s a whole lot to do, now we need a camera to visualize what is happening in our virtual scene.

Adding a camera to the scene

Just looking at the documentation of Three.js, you'll find there are different types of cameras. For our case, we’ll be using a Perspective Camera, which mimics the way how human eyes see. We’ll be passing three props in this camera to specify the Field of View, Aspect Ratio, Near plane, and Far plane of our camera.

  • FOV (Field of view): How far the camera can see?
  • Aspect Ratio: How wide and long will be our viewing screen?
  • Near plane: How close can an object be seen?
  • Far plane: How far can an object be seen?

Note: I just positioned the camera as per my set-up, you need to play with the values passed to get a visual of our model later.

Creating our 3D model

Now the fun part begins ;)
Any 3D object has three components: A skeleton, a skin, and a medium to connect both of them. In three.js we call them, Geometry, Material, and Mesh respectively (you know developers like to use fancy names, lol 😁).

For reference, we’ll be creating a Sphere Geometry, which will take three arguments: Radius (obviously), Width Segments and Height segments.

You must be wondering, what do you mean by the width and height of a sphere? Just take a look :

We are talking about the height and width of these rectangular sectors. This may have cleared your doubts.

Now, let’s add material for our lil’ sphere. The code for the material is self-explanatory, I have given a color, a metallic finish, and a wireframe to our sphere and along with that I have used MeshBasicMaterial, which is one of the standard materials from the Three.js library. You can add your custom materials as well, but that's for the next time ;). Then just pass the geometry and material in mesh to bind them together and add the mesh to the scene, just like this :

Adding a renderer and animating our model

Almost there, just have some patience. Now our model is ready to perform on our stage, but we need to have a buffer to control the time when will our model perform, just like a stage curtain. Similarly, our browser has to know when will our model render on the screen. For that let's create a Renderer. It’s pretty simple,

  • Just set its height and width.
  • Set the Pixel ratio as your device’s pixel ratio to avoid the jaggedness whenever our model renders.
  • Then inject the renderer to our DOM element (here referred to body)

To animate our model we’ll use requestAnimationFrame and call render by passing our sceneand camera as arguments, the code is as :

Your overall code will look like this :

Finally, now let our PLAY BEGIN !! Run npm run dev on your terminal and click on the localhost link, then sit back and enjoy the show 😎 :

Rendering a pre-designed 3D model

Hmm…still not satisfied? Ok, so we’ll bring in a new model to act for our play now. How do we bring a pre-designed 3D model? The answer is GLTFLoader .

So, to be on the same track download the 3D model from here. And extract all the files in the public folder inside the project folder. Your updated folder structure will look like this:

Setting up GLTFLoader

Create a new GLTFloader that will load our 3D model into our virtual scene. Passing the path of our model into the load function which takes an onLoad function as callback and then set up the position and scale of our model. Call the renderer and then animate our model into the loader as :

Adding Orbital Controls

To make our model more dynamic or to make it more reactive to our cursor actions, let's implement some Orbital controls. For that, we need to first import it from the three.js library and pass some arguments. What will be those arguments? Our camera and renderer’s DOM element, this way whenever we try to drag our mouse on the screen, it will make sure to move the camera along with it and update the changes in the renderer’s DOM element.

I have also updated the animate function to rotate our model along the z-axis. Also, added sRBG encoding just makes sure that the colors of our model render perfectly.

After adding a background color to the scene, your code may look like this:

Ready to look at your masterpiece, so what are you waiting for, again run npm run dev and open the development server. Bon appetite 😋 !!

Visit this link: Hostlink, to see what we have created.

If you fall behind any step, you can always refer to my GitHub repo: Pixel-Tank
You can get the set-up code in set-up branch and the final code in main branch.

This blog may have introduced you to Three.js, but there is still a lot to learn. This tool has immense potential, you just need to be creative and build something great with what you have learnt so far. For reference, you can visit these website, to see the actual power of Three.js :

Parting ways…. to meet again :)

From an idea to a reality, this has been an amazing journey, which I have trodden on, getting all types of experiences, good ones, bad ones (aka debugging 😪), but the kick you get after seeing your results never disappoints you. In my words, this is what a developer's life is, it's not a happy one, not a sad one either, but it is a never-ending strive for always building something which will make you a better version of yourself.

If you liked this small adventurous journey, do give 👏 to this article, I would really appreciate that :)

--

--

Gurpreet Singh
tech@iiit-gwalior

Exploring till the end | Web Developer | Technical Writer | Open Sourcer