The Basics to Using Three.js: Build a Cube

Adam Shappy
3 min readMar 22, 2020

--

My first impression of building web applications and websites certainly did not have me imagining 3D interactive objects or games. After being blown away by all the awesome 2D games people were building in my cohort I began to wonder if these same games could be built into a 3D world. A fellow developer introduced me to three.js. Here I will quickly go over what it is and break it down into simple components.

Three.js is a simplistic 3D rendering library that can be implemented into any Javascript project. It uses a technology called WebGL but builds upon it. Without three.js, it can be quite difficult to build any kind of 3D objects with just WebGL. Therefore you can imagine that three.js takes care of all the complicated mathematical code that is inherently involved with 3D rendering and animation. Components like scene, camera, light, and mesh are the four fundamental pieces for our 3D app.

Components of three.js scene
The four fundamental components for 3D rendering in Three.js

As you can see in the sketch above. Without one of these components there wouldn’t be anything to render or in the case of removing light, many objects would lose their dimensionality. I think these type of drawings help demystify the world of 3D tech. If you imagine removing the mesh or cube. You would just have empty space, therefore nothing for the light to illuminate.

So if we wanted to render a very basic object, three.js provides primitive objects such as cubes, spheres, etc. This makes it easier to piece together your own objects on the fly.

General Flow Chart for 3D Cube

Therefor the code for building our 3D cube is simple. We need WebGL Renderer, perspective camera, a scene, directional lighting, mesh (this makes our cube), a box, and MeshPhongMaterial. That’s seven components we need. So lets see what this looks like in code.

You can easily see that the seven components have been implemented here. The result is a 3D cube! But there is one thing missing. The cube isn’t interactive and it isn’t rotating so all you see is one side of a cube giving the impression of a 2D square. A quick fix to this is adding the rotation on the x and y-axis by using the vanilla JS method called request animation frame.

Function to Add Cube Rotation

And there you have it. A rotating 3D cube, with lighting. It isn’t pretty and tutorials exist at three.js to help improve the aesthetic of the cube and it’s responsiveness to screen size changes. For now that concludes my intro into three.js.

--

--

Adam Shappy

Overly enthusiastic outdoor adventurer and programmer.