Comprendre la 3D en Javascript (ThreeJS) en 5 minutes

Understand 3D in Javascript (ThreeJS) in 5 minutes

With a little knowledge in Javascript, you can do incredible things in 3D with ThreeJS. It’s much simpler than it looks and it’s so much fun. The only problem is the first learning barrier. Today, I’m taking that barrier down for you in 5 minutes. After that, all you’ll have to do is have fun.



What is ThreeJS?

ThreeJS is a library in Javascript, created by Mr.doob, that allows you to manipulate 3D objects directly in the browser. What you have to understand is that ThreeJS, via Javascript, allows you to use WebGL in an HTML5 canvas.

WebGL is a Javascript API that allows you to create 2D and 3D graphic rendering.
A canvas is an HTML component that is part of the HTML5 specification and allows to display graphic rendering.

ThreeJS, via Javascript, allows you to drive WebGL, and thus 3D. And the crazy part is that there is no additional installation and/or plugin needed ! Import the the library and voila, the 3D world is opening.





So in summary, we have a Javascript library(ThreeJS) that manipulates a Javascript API to do graphical rendering (WebGL) in an HTML5 component. Easy!

Now you’re going to tell me, why are we using ThreeJS? If it’s actually WebGL, why not write WebGL directly ? The answer is pretty simple.

ThreeJS simplifies and shortens to the extreme the code needed to do whatever you want. ThreeJS does all the complex part for you. You just have to do simple Javascript on your side.

So if you have simple Javascript knowledge, ThreeJS gives you the power to do incredible things in 3D.

But concretely, how does it work?



How does it work?

To understand how ThreeJS works at a high level you need to put yourself in the shoes of a film director. Yes, poof, I’ve just decided, you’re a movie director now.

And to shoot your movie in Javascript, you’re going to need to create and manipulate several key elements.



  • The scene

You can see the scene like the 3D world you’re going to work in. You’re going to arrange objects in this scene. You’re going to create as many objects as you want in your scene via the meshes.




  • The meshes

Meshes are simply the objects that will be present in your scene. You will need to put light on these objects to see them. To see them, you will have to film them. To film them, you need a camera.




  • The camera

As in real life, the camera will show a point of view of your scene. We’re going to talk about field of view (fov), to be precise. By moving the camera, you’re going to move objects in or out of this field of view. It’s what you see in this field of view of this camera that will be sent to the rendering engine.




  • Rendering engine

The rendering engine takes the scene and the camera as parameters. With that, it displays everything in the HTML5 canvas I was telling you about at the beginning. The rendering engine will produce an image each time your screen is refreshed. In general, 60 frames per second. That’s what gives life to your animation!



I guess it can still be pretty abstract at the moment. I have to draw you a picture to make it more concrete. Ok, I’ll use my drawing skills then.





Can you tell i’m backend developer ?

Anyway, it should be much clearer now between the explanations and the drawing. But we’re getting to know each other, I know you want to see code now.



Show the code

As the Hello World app we’ll make it as simple as possible. We’re going to code the schema I made for you just before.

A basic scene with a cube in the middle. Except that instead of the cube, we’re going to put a cylinder, just because I feel like it. We’re going to make it spin on itself and we’re going to put it in the camera’s field of view.

I’m going to comment strongly on each line so that you understand everything that’s going on. I will also frequently talk about the official documentation, so don’t hesitate to read it as you go along.





We start by declaring our scene, without that, nothing is visible! Then the rendering engine for our scene. Without this, no image will be created and displayed to the user. Then we want a camera to film the scene. Here we will use a perspective camera. The options allow us to configure the field of view.



const scene = new THREE.Scene()
const renderer = new THREE.WebGLRenderer()
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)


We already have everything we need to show things now. Let’s create the cylinder via a mesh! To create a mesh we need two things.

The geometric shape that the object will have. Here we want a cylinder so CylinderGeometry is perfect for our needs.

The material of this object. The material is the digital version of real world materials. The materials control the color of the object and the degree of reflection of the surface. Here we put a basic material of red color.

With these two parts we can create our object, add it to the scene and place the camera over it.



const geometry = new THREE.CylinderGeometry(5, 5, 20, 32)
const material = new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true })
const cylinder = new THREE.Mesh(geometry, material)

scene.add(cylinder)
camera.position.z = 20


Then, we’re going to put the rendering engine in full screen and add it in the HTML page via the HTML5 canvas!



renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)


Finally, we’re going to animate things up. We are going to create an animation function that will be called in an infinite loop. Each time we go through this function we’re going to:

  • make the cylinder rotate on itself
  • ask the rendering engine to create and display an image
  • recall this same animation function


function animate() {
    cylinder.rotation.x += 0.01
    cylinder.rotation.y += 0.01

    renderer.render(scene, camera)

    requestAnimationFrame(animate)
}

animate()


And that’s it ! Done ! I put everything in a codepen and let you play with it now.





I tried to make this article a highway for understanding Javascript 3D. I sincerely think that after this first barrier of understanding, you can quickly do incredible things! Go use you new power now.





A few weeks ago, I hadn’t touched 3D in any way, shape or form. Starting from the basic example I just presented to you, in a few days, I created a 3D web experience that takes you through the universe in your browser.





I’m really super proud of it and I invite you to take a look at it. There’s a story, music and it’s amazing. A real show! If you’re even more curious, you have all the source code on my GitHub.



Epilogue

If I can do this kind of thing in a week, that’s proof that anyone can do it. Anything you can imagine as animation is within your reach with your knowledge of Javascript. And now that you have the ThreeJS base, it’s up to you to see if the adventure tempts you.

Written by

jesuisundev
I'm a dev. Right now i'm Backend Developer / DevOps in Montreal. Dev is one of my passions and I write as I speak. I talk to you daily on my Twitter. You can insult me at this e-mail or do it directly in the comments below. There's even a newsletter !

1 thought on “Understand 3D in Javascript (ThreeJS) in 5 minutes”

Leave a reply

Your email address will not be published. Required fields are marked *