Hello █████ Cube: THREE.js Scene in Angular

Anurag Srivastava
Geek Culture
Published in
7 min readSep 4, 2021

Three.js is a JavaScript library used to create and display animated 3D computer graphics on a web browser, compatible with the HTML5 canvas element, WebGL, and SVG.

three.js in angular
Three.js in Angular

In this tutorial, we will go through a simple example. We’ll render a 3D Cube, and we’ll learn the fundamentals of Three.js and integrate the Three.js scene in Angular.

How Three.js Works
How Three.js Works

Project Setup

To follow along with this tutorial it is necessary to have node installed on your computer: Node.js.

➡ Install Node.js and follow on-screen wizard steps.(as per use 32/64 bit).

To start, open a terminal of your choice and create a new angular project. (You can skip this step if you want to add three.js in an existing project)

➡ To create Angular project, you need to first install Angular CLI

npm install -g @angular/cli

installing angular cli
install angular cli

➡ You are good to start using the CLI to create an angular web app. Let us create our project by typing in the below command in the terminal.

ng new angular-three

creating angular project
create angular project

➡ After the CLI has completed setting up the project, we change our current directory into the project directory and install three.js as a dependency by typing in the below command in the terminal.

cd angular-three

npm install — save three

➡ By using the below command you can install the type definitions of Three.js.

npm install — save @types/three

Three.js is now successfully added to our Angular project and ready to use. We are going to build a basic scene with a camera and a cube mesh to test if it works.

Let us first create an angular component which would consist of an HTML file where we are going to render the 3D object, a Typescript file (.ts) where we would import Three.js functionality and a CSS or SCSS style file. Type in the below command to create a Cube Component.

ng generate component cube

Open up the HTML file and add a canvas into our empty scene. We can add the canvas in whatever size we need it in the HTML template.

adding canvas in cube.component.html
adding canvas in cube.component.html

With this small step out of the way, we can switch our attention to the Typescript file, where the actual work still has to be done to get our 3D scene set.

Programming the Three.js Scene

Now to Integrate Three.js with Angular, you must import the Three.js library to the component in which you are going to render the 3D object, i.e cube.component.ts.

importing three.js in ts file
import three.js at the top

Get the reference of the canvas we added in the HTML file using

@ViewChild(‘canvas’) private canvasRef: ElementRef;

canvas reference in .ts file

Cube properties:

  • rotationSpeedX :- rotation speed of cube on x-asis
  • rotationSpeedY :- rotation speed of cube on y-asis
  • size :- size of the cube
  • texture :- if you want to add a texture to your cube
Cube Properties

Stage properties:

  • cameraZ :- camera position on the z-axis
  • fieldofview :- field of view of the camera
near and far clipping plane
near and far clipping plane
  • nearClippingPlane
  • farClipingPlane

Near and far clipping planes are imaginary planes located at two particular distances from the camera along the camera’s sight line. Only objects between a camera’s two clipping planes are rendered in that camera’s view.

stage properties
stage properties

Why are we changing the camera position?

The element which is added to the scene spawns on the location (0, 0, 0) by default, which is why we need to move the camera or the element so that we can see the element on the canvas.

Let us create some helper properties which would help us create the scene.

  • declare a camera variable of type perspective camera :- it gives a 3d view where things in the distance appear smaller than things up close. The Perspective Camera defines a frustum.
  • initialize getter function to get the canvas element
  • initialize a geometry variable
  • initialize a material variable which would load the texture image
  • initialize the cube, and declare renderer and scene as shown below
helper properties
helper properties

What is a Geometry?

A geometry is a rendered shape that we’re building — like a box. A geometry can be build from vertices or we can use a predefined one.

The BoxGeometry is the most basic predefined option. We only have to set the width, height, and depth of the box and that’s it. There are other predefined geometries as well. We can easily define a plane, a cylinder, a sphere, or even an icosahedron.

three.js geometries
Three.js geometries

Working with Material

A material describes the appearance of an object. Here we can define things like texture, color, or opacity.

In this example we are only going to set a texture. There are still different options for materials. The main difference between most of them is how they react to light. The simplest one is the MeshBasicMaterial. This material doesn’t care about light at all, and each side will have the same color. It might not be the best option, though, as you can’t see the edges of the box.

The simplest material that cares about light is the MeshLambertMaterial. This will calculate the color of each vertex, which is practically each side. But it doesn’t go beyond that.

three.js mesh materials
three.js mesh materials

Positioning a Mesh (cube in our case)

We can position it within the scene and set a rotation by each axis. Later if we want to animate objects in the 3D space we will mostly adjust these values. For positioning we use the same units that we used for setting the size. It doesn’t matter if you are using small numbers or big numbers, you just need to be consistent in your own world. For the rotation we set the values in radians. So if you have your values in degrees you have to divide them by 180° then multiply by PI.

Let us create the scene now, the scene is where we will add different elements that we want to work with like camera, cube, etc. Create a function as shown below:

creating the scene
creating the scene

Initialize a function animateCube. Calling this function adds cube rotations on x-axis and y-axis in an incremental approach.

function to animate the cube
animateCube function

If we try to start the application, we would not see anything yet because for Three.js to work and provide us with something to see. We need to define a WebGLRenderer. This is the piece that is capable of rendering the actual image into an HTML canvas when we provide a scene and a camera. This is also where we can set the actual size of this canvas — the width and height of the canvas in pixels as it should appear in the browser.

Let us create a renderer function. Create a function as shown below. Pass the canvas element into the renderer we declared earlier, set the renderer engine pixel ratio and set its size. Call a recursive render function to generate the animation loop.

start the rendering loop
start the rendering loop

Finally, call the createScene() and startRenderingLoop() function in ngAfterViewInit() and start the project using ng serve in the terminal.

calling the scene function
final view in web browser
calling the scene and render loop

The code is written in such a way the you can call this cube component in any parent component and change the parameters from the parent component.

--

--

Anurag Srivastava
Geek Culture

I can help you with building websites mobile apps, brand identity, photo edits and maybe some crafts.