Skip to content
ImagineWorld

The Basic Components that Make up a Three.js Application

node_idnode-book_learn-three-js_chapter-02-the-basic-components-that-make-up-a-three-js-application
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleThe Basic Components that Make up a Three.js Application
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — The Basic Components that Make up a Three.js Application

Section titled “Chapter 2 — The Basic Components that Make up a Three.js Application”

In the previous chapter, you learned about the basics of Three.js. We looked at a couple of examples, and you created your first complete Three.js application. In this chapter, we’ll dive a bit deeper into Three.js and explain the basic components that make up a Three.js application.

By the end of this chapter, you’ll have learned how to use the basic components that are used in every Three.js application and should be able to create simple scenes using these standard components. You should also feel comfortable working with Three.js applications that use the more advanced objects, since the approach used by Three.js for simple and advanced components is the same.

In this chapter, we will cover the following topics:

  • Creating a scene
  • How geometries and meshes are related
  • Using different cameras for different scenes

We’ll start by looking at how you can create a scene and add objects.

In Chapter 1, Creating Your First 3D Scene with Three.js, you created a THREE.Scene, so you already know some of the basics of Three.js. We saw that for a scene to show anything, we need four different types of objects:

  • Camera: This determines which part of THREE.Scene is rendered onscreen.
  • Lights: These have an effect on how materials are shown and are used when creating shadow effects (discussed in detail in Chapter 3, Working with Light Sources in Three.js).
  • Meshes: These are the main objects that are rendered from the perspective of the camera. These objects contain the vertices and faces that make up the geometry (for example, a sphere or a cube) and contain a material, which defines what the geometry looks like.
  • Renderer: This uses the camera and the information in the scene to draw (render) the output on the screen.

THREE.Scene serves as the main container for the lights and the meshes you want to render. THREE.Scene itself doesn’t have that many options and functions.

THREE.Scene is a structure that is sometimes also called a scene graph. A scene graph can hold all the necessary information of a graphical scene. In Three.js, this means that a THREE.Scene contains all the objects necessary for rendering. It is interesting to note that a scene graph, as the name implies, isn’t just an array of objects; a scene graph consists of a set of nodes in a tree structure. As we’ll see in Chapter 8, Creating and Loading Advanced Meshes and Geometries, Three.js provides objects you can use to create groups of different meshes or lights. The main object you use for that, which you can use to create a scene graph, is the THREE.Group. As the name implies, this object allows you to group objects together. A THREE.Group extends from another base class in Three.js called THREE.Object3D, which provides a set of standard functions to add and modify children. THREE.Mesh and THREE.Scene both also extend from a THREE.Object3D so you could also use those to create a nested structure. But it’s convention, and also more semantically correct, to use THREE.Group to build up the scene graph.

The best way to explore the functionality of a scene is by looking at an example. In the source code for this chapter, you can find the chapter-2/basic-scene.html example. We’ll use this example to explain the various functions and options a scene has. When we open this example in the browser, the output will look similar to what’s shown in the next screenshot (remember that you can use the mouse to move, zoom, and pan around the rendered scene):

Figure 2.1 – Basic scene setup

The preceding figure looks like the examples we saw in Chapter 1, Creating Your First 3D Scene with Three.js. Even though the scene looks pretty empty, it already contains a few objects:

  • We’ve got THREE.Mesh, which represents the floor area you can see
  • We’re using THREE.PerspectiveCamera to determine what we’re looking at
  • We’ve added THREE.AmbientLight and THREE.DirectionalLight to provide lighting

The source code for this example can be found in basic-scene.js, and we can use code from bootstrap/bootstrap.js, bootstrap/floor.js, and bootstrap/lighting.js since this is a generic scene setup we use throughout this book. What happens in all these files can be simplified as in the following code:

// create a camera
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
// create a renderer
const renderer = new THREE.WebGLRenderer({ antialias: true
});
// create a scene
const scene = new THREE.Scene();
// create the lights
scene.add(new THREE.AmbientLight(0x666666));
scene.add(THREE.DirectionalLight(0xaaaaaa));
// create the floor
const geo = new THREE.BoxBufferGeometry(10, 0.25, 10, 10,
10, 10);
const mat = new THREE.MeshStandardMaterial({ color:
0xffffff,});
const mesh = new THREE.Mesh(geo, mat);
scene.add(mesh);

As you can see in the preceding code, we create THREE.WebGLRenderer and THREE.PerspectiveCamera, since we always need those. Next, we create a THREE.Scene and just add all the objects that we want to use. In this case, we add two lights and a single mesh. Now, we have all the components to start up a render loop, as we’ve already seen in Chapter 1, Creating Your First 3D Scene with Three.js.

Before we look at the THREE.Scene object in more depth, we’ll first explain what you can do in the demo, and after that, look at the code. Open the chapter-2/basic-scene.html example in your browser and look at the Controls menu in the upper-right corner, which you can see in the following screenshot:

Figure 2.2 – Basic scene setup with Cubemap background

With these Controls, you can add cubes to the scene and remove the cube that was last added. It also allows you to change the background of the scene and set the material and the environment map for all the objects in the scene. We’ll explore these various options and how you can use them to configure a THREE.Scene. We’ll start by looking at how you can add and remove THREE.Mesh objects to and from a scene. The following code shows the function we call when you click on the addCube button:

const addCube = (scene) => {
const color = randomColor();
const pos = randomVector({
xRange: { fromX: -4, toX: 4 },
yRange: { fromY: -3, toY: 3 },
zRange: { fromZ: -4, toZ: 4 },
});
const rotation = randomVector({
xRange: { fromX: 0, toX: Math.PI * 2 },
yRange: { fromY: 0, toY: Math.PI * 2 },
zRange: { fromZ: 0, toZ: Math.PI * 2 },
});
const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const cubeMaterial = new THREE.MeshStandardMaterial({
color: color,
roughness: 0.1,
metalness: 0.9,
});
const cube = new THREE.Mesh(geometry, cubeMaterial);
cube.position.copy(pos);
cube.rotation.setFromVector3(rotation);
cube.castShadow = true;
scene.add(cube);
};

Let us understand the preceding code in detail:

  • First, we have determined some random settings for the cube that will be added: a random color (by calling the randomColor() helper function), a random position, and a random rotation. These last two are randomly generated by calling randomVector().
  • Next, we create the geometry we want to add to the scene: a cube. We just create a new THREE.BoxGeometry for this, define a material (THREE.MeshStandardMaterial in this example), and combine these two into THREE.Mesh. We use random variables to set the cube’s position and rotation.
  • Finally, this THREE.Mesh can then be added to the scene by calling scene.add(cube).

A new element that we have introduced in the preceding code is that we also give the cube a name using the name attribute. The name is set to cube-, appended with the number of objects currently in the scene (scene.children.length). A name is very useful for debugging purposes but can also be used to directly access an object from your scene. If you use the THREE.Scene.getObjectByName(name) function, you can directly retrieve a specific object and, for instance, change its location without having to make the JavaScript object a global variable.

There might also be situations where you want to remove an existing object from a THREE.Scene. Since a THREE.Scene exposes all its children through the children property, we can just use the following simple code to remove the last child added:

const removeCube = (scene) => {
scene.children.pop();
};

Three.js provides other helpful functions for the THREE.Scene too, related to working with the children of the scene:

  • add: We’ve already seen this function, which adds the provided object to the scene. If it was previously added to a different THREE.Object3D, it’ll be removed from that object.
  • Attach: This is similar to add, but if you use it, any rotations or translations applied to this object will be kept.
  • getObjectById: When you add an object to a scene, it gets an ID. The first one gets 1, the second one 2, and so on. With this function, you can get a child based on this ID.
  • getObjectByName: This returns an object based on its name property. The name is something you can set on an object – this is in contrast with the id property, which is assigned by Three.js.
  • Remove: This removes this object from the scene.
  • Clear: This removes all the children from the scene.

Note that the preceding functions are actually from the base object that the THREE.Scene extends from: the THREE.Object3D.

Throughout the book, we’ll use these functions if we want to manipulate the children of a scene (or in THREE.Group, as we’ll explore later on.)

Besides the functionality to add and remove objects, a THREE.Scene also provides a couple of other settings. The first one we’ll look at is adding fog.

The fog property lets you add a fog effect to the complete scene; the farther an object is from the camera, the more it will be hidden from sight. This is shown in the following screenshot:

Figure 2.3 – Using fog to hide objects

To best see the effect of the added fog, use the mouse to zoom in and out, and you’ll see the cubes being affected by the fog. Enabling fog is really easy in Three.js. Just add the following line of code after you’ve defined your scene:

scene.fog = new THREE.Fog( 0xffffff, 1, 20 );

Here, we define white fog (0xffffff). The other two properties can be used to tune how the mist appears. The 1 value sets the near property, and the 20 value sets the far property. With these properties, you can determine where the mist starts and how fast it gets denser. With the THREE.Fog object, the fog increases linearly. In the chapter-02/basic-scene.html sample, you can modify these properties by using the menu on the right of the screen to see how these settings affect what you see onscreen.

There is also an alternative fog implementation provided by Three.js, THREE.FogExp2:

scene.fog = new THREE.FogExp2( 0xffffff, 0.01 );

This time, we don’t specify near and far, but just the color (0xffffff) and the mist’s density (0.01). Usually, it’s best to experiment a bit with these properties to get the effect you want.

Another interesting feature of a scene is that you can configure a background.

We’ve already seen that we can change the background color by setting clearColor of WebGLRenderer like this: renderer.setClearColor(backgroundColor). You can also use the THREE.Scene object to change the background. For this, you’ve got three options:

  • Option 1: You can use a solid color.
  • Option 2: You can use a texture, which is basically an image, stretched out to fill the complete screen. (More on textures in Chapter 10, Loading and Working with Textures.)
  • Option 3: You can use an environment map. This is also a kind of texture, but one that completely encompasses the camera, and moves around when you change the camera orientation.

Note that this sets the background color of the HTML canvas we’re rendering to and not the background color of the HTML page. If you want to have a transparent canvas, you need to set the alpha property of the renderer to true:

new THREE.WebGLRenderer({ alpha: true }}

In the chapter-02/basic-scene.html menu on the right, there is a dropdown that shows all these different settings. If you select the Texture option from the backGround dropdown, you’ll see the following:

Figure 2.4 – Background using a texture

We’ll cover textures and cubemaps in much more detail in Chapter 10, Loading and Working with Textures. But we’ll have a quick look now at how to configure these and a simple background color for the scene (the source for this can be found in controls/scene-controls.js):

// remove any background by setting the background to null
scene.background = null;
// if you want a simple color, just set the background to a
color
scene.background = new THREE.Color(0x44ff44);
// a texture can be loaded with a THREE.TextureLoader
const textureLoader = new THREE.TextureLoader();
textureLoader.load(
"/assets/textures/wood/abstract-antique-
backdrop-164005.jpg",
(loaded) => {
scene.background = loaded;
}
// a cubemap can also be loaded with a THREE.TextureLoader
textureLoader.load("/assets/equi.jpeg", (loaded) => {
loaded.mapping = THREE.EquirectangularReflectionMapping;
scene.background = loaded;
});

As you can see from the preceding code, you can assign either null, THREE.Color, or THREE.Texture to the background property of the scene. Loading a texture or a cubemap is done asynchronously, so, we have to wait for THREE.TextureLoader to load the image data before we can assign it to the background. In the case of the cubemap, we need to take an extra step and tell Three.js what kind of texture we’ve loaded. We will go into more detail in Chapter 10, Loading and Working with Textures, when we dive into the details of how textures work.

If you look back at the beginning of the following code section, you will see how we created the cubes that we added to the scene:

const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const cubeMaterial = new THREE.MeshStandardMaterial({
color: color,
roughness: 0.1,
metalness: 0.9,
});
const cube = new THREE.Mesh(geometry, cubeMaterial);

In the preceding code, we have created a geometry and specified a material. The THREE.Scene object also provides a way to force the meshes in the scene to use the same material. In the following section, we’ll explore how that works.

A THREE.Scene has two properties that affect the material of the meshes in the scene. The first one is the overrideMaterial property. First, let’s demonstrate how this works. On the chapter-02/basic-scene.html page, you can click on the Toggle Override Material button. This will change the material of all the meshes in the scene to a THREE.MeshNormalNormal material:

Figure 2.5 – Override mesh materials with MeshNormalMaterial

As you can see in the preceding figure, all the objects (including the ground floor) now use the same material – in this case, THREE.MeshNormalMaterial. This material colors each face of the mesh based on its orientation (its normal vector) to the camera. This can be very easily done in code by just calling scene.overrideMaterial = new THREE.MeshNormalMaterial();.

Besides applying a complete material to the scene, Three.js also provides a way to set the environment map property of each mesh’s material to the same value. An environment map simulates the environment (for instance, a room, outdoors, or a cave) the meshes are in. The environment map can be used to create reflections on the meshes to make them feel more real.

We’ve already seen how we can load an environment map in the previous section on backgrounds. If we want all our materials to use an environment map for more dynamic reflections and shading, we can assign that loaded environment map to the environment property of a scene:

textureLoader.load("/assets/equi.jpeg", (loaded) => {
loaded.mapping = THREE.EquirectangularReflectionMapping;
scene.environment = loaded;
});

The best way to demonstrate the preceding code is by toggling the Toggle Environment button from the chapter-02/basic-scene.html example. If you now zoom in close to the cubes, you can see that their faces reflect part of the environment and aren’t a solid color anymore:

Figure 2.6 – Set the environment map to all the meshes in the scene

Now that we’ve discussed the basic container for all the objects we want to render, in the next section, we’ll take a closer look at the objects (THREE.Mesh combining THREE.Geometry and a material) that you can add to the scene.

In each of the examples so far, you’ve seen geometries and meshes being used. For instance, to create a sphere and add it to the scene, we used the following:

const sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
const sphereMaterial = new THREE.MeshBasicMaterial({color:
0x7777ff);
const sphere = new THREE.Mesh(sphereGeometry,
sphereMaterial);
scene.add(sphere);

We defined the geometry (THREE.SphereGeometry), which is the shape of an object, and its material (THREE.MeshBasicMaterial), and we combined these two in a mesh (THREE.Mesh) that can be added to a scene. In this section, we’ll take a closer look at geometries and meshes. We’ll start with geometries.

The properties and functions of a geometry

Section titled “The properties and functions of a geometry”

Three.js comes with a large set of geometries out of the box that you can use in your 3D scene. Just add a material, create a mesh, and you’re pretty much done. The following screenshot, from the chapter-2/geometries example, shows a couple of the standard geometries available in Three.js:

Figure 2.7 – Some of the basic geometries available in the scene

In Chapter 5, Learning to Work with Geometries, and Chapter 6, Exploring Advanced Geometries, we’ll explore all the basic and advanced geometries that Three.js has to offer. For now, we’ll look in greater detail at what a geometry actually is.

A geometry in Three.js, and in most other 3D libraries, is basically a collection of points in a 3D space, also called vertices (where a single point is called a vertex), and a number of faces connecting those points together. Take, for example, a cube:

  • A cube has eight corners. Each of these corners can be defined as an x-, y-, and z- coordinate. So, each cube has eight points in a 3D space.
  • A cube has six sides, with a vertex at each corner. In Three.js, a face always consists of three vertices that make a triangle (which has three edges). So, in the case of a cube, each side consists of two triangles to make the complete side. An example of how that looks can be seen in Figure 2*.7* by looking at the red cube.

When you use one of the geometries provided by Three.js, you don’t have to define all the vertices and faces yourself. For a cube, you only need to define the width, height, and depth. Three.js uses that information and creates a geometry with eight vertices in the correct position and with the correct number of faces (12 in the case of a cube – 2 triangles per side). Even though you’d normally use the geometries provided by Three.js or generate them automatically, you can still create geometries completely by hand using vertices and faces, although this can quickly become complex, as you can see in the following lines of code:

const v = [
[1, 3, 1],
[1, 3, -1],
[1, -1, 1],
[1, -1, -1],
[-1, 3, -1],
[-1, 3, 1],
[-1, -1, -1],
[-1, -1, 1]]
const faces = new Float32Array([
...v[0], ...v[2], ...v[1],
...v[2], ...v[3], ...v[1],
...v[4], ...v[6], ...v[5],
...v[6], ...v[7], ...v[5],
...v[4], ...v[5], ...v[1],
...v[5], ...v[0], ...v[1],
...v[7], ...v[6], ...v[2],
...v[6], ...v[3], ...v[2],
...v[5], ...v[7], ...v[0],
...v[7], ...v[2], ...v[0],
...v[1], ...v[3], ...v[4],
...v[3], ...v[6], ...v[4]
]);
const bufferGeometry = new THREE.BufferGeometry();
bufferGeometry.setAttribute("position", new THREE.BufferAttribute(faces, 3));
bufferGeometry.computeVertexNormals();

The preceding code shows how to create a simple cube. We define the points (the vertices) that make up this cube in the v array. From these vertices, we can create the faces next. In Three.js, we need to provide all the faces information in one large Float32Array. As we mentioned, a face consists of three vertices. So, for each face, we need to define nine values: the x, y, and z of each vertex. Since we’ve got three vertices per face, we have nine values. To make it a little bit easier to read, we use the ... (spread) operator from JavaScript to add the individual values of each vertex to the array. So, ...v[0], ...v[2], ...v[1] will result in the following values in the array: 1, 3, 1, 1, -1, 1, 1, ``3, 1.

Note that you have to take care of the sequence of the vertices used to define the faces. The order in which they are defined determines whether Three.js thinks it is a front-facing face (a face facing the camera) or a back-facing face. If you create faces, you should use a clockwise sequence for front-facing faces and a counter-clockwise sequence if you want to create a back-facing face.

In our example, we have used a number of vertices to define the six sides of the cube, with two triangles for each face. In previous versions of Three.js, you could also use a quad instead of a triangle. A quad uses four vertices instead of three to define the face. Whether using quads or triangles is better is a heated debate raging in the 3D modeling world. Basically though, using quads is often preferred during modeling since they can be more easily enhanced and smoothed than triangles. For rendering and game engines though, working with triangles is often easier since every shape can be rendered very efficiently using triangles.

Using these vertices and faces, we can now create a new instance of THREE.BufferGeometry and assign the vertices to the position attribute. The last step is to call computeVertexNormals() on the geometry we have created. When we call this function, Three.js determines the normal vector for each of the vertices and for the faces. This is the information Three.js uses to determine how to color the faces based on the various lights in the scene (which you can easily visualize if you use THREE.MeshNormalMaterial).

With this geometry, we can now create a mesh, just like we saw earlier. We’ve created an example that you can use to play around with the position of the vertices, which also shows the individual faces. In our chapter-2/custom-geometry example, you can change the position of all the vertices of a cube and see how the faces react. This is shown in the following screenshot:

Figure 2.8 – Move vertices around to change the shape

This example, which uses the same setup as all our other examples, has a render loop. Whenever you change one of the properties in the drop-down control box, the cube is rendered based on the changed position of one of the vertices. This isn’t something that works out of the box. For performance reasons, Three.js assumes that the geometry of a mesh won’t change during its lifetime. For most geometries and use cases, this is a very valid assumption. If you, however, change the backing array (in this case, the const faces = new Float32Array([...]) array), we need to tell Three.js that something has changed. You can do that by setting the needsUpdate property of the relevant attribute to true. This will look something like the following:

mesh.geometry.attributes.position.needsUpdate = true;
mesh.geometry.computeVertexNormals();

Note that in the case of updated vertices, it is also a good idea to recalculate the normal vectors, to make sure the materials are also rendered correctly. More information on what a normal vector is and why it is important will be explained in Chapter 10, Loading and Working with Textures.

There is one button from the chapter-2/custom-geometry menu that we haven’t addressed yet. In the menu on the right, there is a clone button. We mentioned that the geometry defines the form and shape of an object, and combined with a material, we create an object that can be added to the scene to be rendered by Three.js. With the clone() function, as the name implies, we can make a copy of the geometry and, for instance, use it to create a different mesh with a different material. In the same example, chapter-2/custom-geometry, you can see a clone button at the top of the control GUI, as in the following screenshot:

Figure 2.9 – Make a clone of the geometry

If you click on this button, a clone (copy) will be made of the geometry as it currently is; then, a new object will be created with a different material, and finally, the object will be added to the scene. The code for this is as follows:

const cloneGeometry = (scene) => {
const clonedGeometry = bufferGeometry.clone();
const backingArray = clonedGeometry.getAttribute
("position").array;
// change the position of the x vertices so it is placed
// next to the original object
for (const i in backingArray) {
if ((i + 1) % 3 === 0) {
backingArray[i] = backingArray[i] + 3;
}
}
clonedGeometry.getAttribute("position").needsUpdate =
true;
const cloned = meshFromGeometry(clonedGeometry);
cloned.name = "clonedGeometry";
const p = scene.getObjectByName("clonedGeometry");
if (p) scene.remove(p);
scene.add(cloned);
};

As you can see in the preceding code, we use the clone() function to clone bufferGeometry. Once cloned, we make sure to update the x value of each vertex so the clone is put in a different position than the original one (we could also have used translateX, which we explain in the following section of this chapter). Next, we create a THREE.Mesh, remove the cloned mesh if it is there, and add the new clone. To create the new mesh, we use a custom function called meshFromGeometry. As a quick sidestep, let’s look at how that is implemented as well:

const meshFromGeometry = (geometry) => {
var materials = [
new THREE.MeshBasicMaterial({ color: 0xff0000,
wireframe: true }),
new THREE.MeshLambertMaterial({
opacity: 0.1,
color: 0xff0044,
transparent: true,
}),
];
var mesh = createMultiMaterialObject(geometry, materials);
mesh.name = "customGeometry";
mesh.children.forEach(function (e) {
e.castShadow = true;
});
return mesh;
};

If you look back at this example, you can see a transparent cube and the lines (the edges) that make up our geometry. To do this, we create a multi-material mesh. This means that we tell Three.js to use two different materials in a single mesh. For this, Three.js provides a nice helper function called createMultiMaterialObject, which does what the name implies. Based on a geometry and a list of materials, it creates an object that we can add to the scene. There is one thing you need to know though when working with the results from a createMultiMaterialObject call. What you get back isn’t a single mesh; it is a THREE.Group, a container object that, in this case, contains a separate THREE.Mesh for each of the materials we provide. So, when rendering the mesh, it looks like a single object, but it actually comprises multiple THREE.Mesh objects rendered on top of one another. This also means that if we want to have shadows, we need to enable this for each of the meshes inside the group (which is what we did in the preceding code fragment).

In the preceding code, we used createMultiMaterialObject from the THREE.SceneUtils object to add a wireframe to the geometry we created. Three.js also provides an alternative way of adding a wireframe using THREE.WireframeGeometry. Assuming you have a geometry called geom, you can create a wireframe geometry from that: const wireframe = new THREE.WireframeGeometry(geom);. Next, you can draw the lines of this geometry, using the Three.LineSegments object, by first creating a const line = new THREE.LineSegments(wireframe) object, and then adding it to the scene: scene.add(line). Since this helper internally is just a THREE.Line object, you can style how the wireframe appears. For instance, to set the width of the wireframe lines, use line.material.linewidth = 2;.

We’ve already looked a bit at the THREE.Mesh object. In the next section, we’ll dive a bit deeper into what you can do with it.

We’ve already learned that to create a mesh, we need a geometry and one or more materials. Once we have a mesh, we add it to the scene and it’s rendered. There are a couple of properties you can use to change where and how this mesh appears on the scene. In our first example, we’ll look at the following set of properties and functions:

  • position: This determines the position of the object relative to the position of its parent. Most often, the parent of an object is a THREE.Scene object or a THREE.Group object.
  • rotation: With this property, you can set the rotation of an object around any of its own axes. Three.js also provides specific functions for rotations around a single axis: rotateX(), rotateY(), and rotateZ().
  • scale: This property allows you to scale the object around its x-, y-, and z-a xes.
  • translateX() / translateY() and translateZ(): This property moves the object by a specified amount along the corresponding axis.
  • lookAt(): This property points the object to a specific vector in space. This is an alternative to setting the rotation manually.
  • visible: This property determines whether this mesh should be rendered or not.
  • castShadow: This property determines whether this mesh casts shadows when it is hit by light. By default, meshes don’t cast shadows.

When we’re rotating an object, we’re rotating around an axis. In a 3D scene, there are multiple spaces that have an axis you can rotate around. The rotateN() functions rotate the object around the axis in local space. This means the object rotates around the axis of its parent. So, when you add an object to the scene, the rotateN() functions will rotate that object around the main axis of the scene. When it is part of a nested group, these functions will rotate the object around the axis of its parent, which is normally the behavior you’re looking for. Three.js also has a specific rotateOnWorldAxis, which allows you to rotate an object around the axis of the main THREE.Scene regardless of the actual parent of the object. Finally, you can also force the object to rotate around its own axis (this is called object space) by calling the rotateOnAxis function.

As always, we have an example ready for you that will allow you to play around with these properties. If you open chapter-2/mesh-properties in your browser, you get a drop-down menu where you can alter all these properties and directly see the result, as shown in the following screenshot:

Figure 2.10 – Mesh properties

Let me walk you through the properties; I’ll start with the position property.

Setting the location of the mesh with the position property

Section titled “Setting the location of the mesh with the position property”

We’ve already seen this property a couple of times, so let’s quickly address it. With this property, you set the x-, y-, and z-c oordinates of the object relative to its parent. We’ll get back to this in Chapter 5, Learning to Work with Geometries, when we look at grouping objects. We can set an object’s position property in three different ways. We can set each coordinate directly:

cube.position.x = 10;
cube.position.y = 3;
cube.position.z = 1;

However, we can also set all of them at once, as follows:

cube.position.set(10,3,1);

There is also a third option. The position property is a THREE.Vector3 object. That means we can also do the following to set this object:

cube.position = new THREE.Vector3(10,3,1)

Next on the list is the rotation property. You’ve already seen this property being used a couple of times here and in Chapter 1, Creating Your First 3D Scene with Three.js.

Defining the rotation of the mesh with the rotation property

Section titled “Defining the rotation of the mesh with the rotation property”

With this property, you set the rotation of the object around one of its axes. You can set this value in the same manner as we did the position. A complete rotation, as you might remember from math class, is 2π. You can configure this in Three.js in a couple of different ways:

cube.rotation.x = 0.5*Math.PI;
cube.rotation.set(0.5*Math.PI, 0, 0);
cube.rotation = new THREE.Vector3(0.5*Math.PI,0,0);

If you want to use degrees (from 0 to 360) instead, we’ll have to convert those to radians. This can be easily done as follows:

const degrees = 45;
const inRadians = degrees * (Math.PI / 180);

In the preceding code block, we’ve done the conversion ourselves. Three.js also provides the MathUtils class, which provides a lot of helpful conversions, including one that does the same thing as we did in the preceding code block. You can play around with this property using the chapter-2/mesh-properties example.

The next property on our list is one we haven’t talked about: scale. The name pretty much sums up what you can do with this property. You can scale the object along a specific axis. If you set the scale to a value less than one, the object will shrink, as shown in the following screenshot:

Figure 2.11 – Use scale to shrink a mesh

When you use values greater than one, the object will become larger, as shown in the following screenshot:

Figure 2.12 – Use scale to grow a mesh

The next part of the mesh that we’ll look at is the translate property.

Changing the position using the translate property

Section titled “Changing the position using the translate property”

With translate, you can also change the position of an object, but instead of defining the absolute position where you want the object to be, you define the distance the object should move, relative to its current position. For instance, we have a sphere that is added to a scene, and its position has been set to (1, 2, 3). Next, we translate the object along its x-a xis: translateX(4). Its position will now be (5, 2, 3). If we want to restore the object to its original position, we use translateX(-4). In the chapter-2/mesh-properties example, there is a menu tab called translate. From there, you can experiment with this functionality. Just set the translate values for x, y, and z and hit the translate button. You’ll see the object being moved to a new position based on these three values.

The last two properties we’ll look at are used to remove the object completely, by setting the visible property to false, and disabling whether this object casts shadows by setting the castShadow property to false. When you click on these buttons, you’ll see the cube becomes invisible and visible, and you can disable it from casting shadows.

For more information on meshes, geometries, and what you can do with these objects, check out Chapter 5, Learning to Work with Geometries, and Chapter 7, Points and Sprites.

So far, we’ve looked at THREE.Scene, the main object that holds all the objects that we want to render, and we’ve looked in detail at what a THREE.Mesh is, and how you can create a THREE.Mesh and position it in a scene. In previous sections, we’ve already used a camera to determine what part of THREE.Scene you wanted to render but haven’t explained in detail yet how you can configure a camera. In the next section, we’ll dive into those details.

Using different cameras for different scenes

Section titled “Using different cameras for different scenes”

There are two different camera types in Three.js: the orthographic camera and the perspective camera. Note that Three.js also provides a couple of very specific cameras for creating scenes that can be viewed using 3D glasses or VR gear. We won’t go into detail about those cameras in this book, since they work exactly the same as the cameras explained in this chapter. If you’re interested in these cameras, Three.js provides a few standard examples:

If you’re looking for simple VR cameras, you can use THREE.StereoCamera to create 3D scenes that are rendered side to side (standard stereo effect), use a parallel barrier (as 3DS provides), or provide an anaglyph effect where the different views are rendered in different colors. Alternatively, Three.js has some experimental support for the WebVR standard, which is supported by a number of browsers (for more info, see https://webvr.info/developers/). To use this, not that much needs to change. You just set renderer.vr.enabled = true, and Three.js will handle the rest. The Three.js website has a couple of examples where this property and some other features of Three.js’s support for WebVR are demonstrated: https://threejs.org/examples/.

For now, we’ll focus on the standard perspective and orthographic cameras. The best way to explain the differences between these cameras is by looking at a couple of examples.

An orthographic camera versus a perspective camera

Section titled “An orthographic camera versus a perspective camera”

In the examples for this chapter, you can find a demo called chapter2/cameras. When you open this example, you’ll see something like the following:

Figure 2.13 – Perspective camera view

This preceding screenshot is called a perspective view and is the most natural view. As you can see from this figure, the farther away the cubes are from the camera, the smaller they are rendered. If we change the camera to the other type supported by Three.js, the orthographic camera, you’ll see the following view of the same scene:

Figure 2.14 – Orthographic camera view

With the orthographic camera, all the cubes are rendered the same size; the distance between an object and the camera doesn’t matter. This is often used in 2D games, such as old versions of Civilization and SimCity 4:

Figure 2.15 – Orthographic usage in SimCity 4

Let’s first look a bit closer at THREE.PerspectiveCamera. In the example, you can set a number of properties that define what is shown through the lens of the camera:

  • fov: The Field of View (FOV) is the part of the scene that can be seen from the position of the camera. Humans, for instance, have an almost 180-degree FOV, while some birds even have a complete 360-degree FOV. But since a normal computer screen doesn’t completely fill our vision, a smaller value is often chosen. Generally, for games, a FOV of between 60 and 90 degrees is chosen. Good default: 50
  • aspect: This is the aspect ratio between the horizontal and vertical sizes of the area where we’re rendering the output. In our case, since we use the entire window, we just use that ratio. The aspect ratio determines the difference between the horizontal FOV and the vertical FOV. Good default: window.innerWidth / window.innerHeight
  • near: The near property defines how close to the camera Three.js should render the scene. Normally, we set this to a very small value to directly render everything from the position of the camera. Good default: 0.1
  • far: The far property defines how far the camera can see from the position of the camera. If we set this too low, part of our scene might not be rendered, and if we set it too high, in some cases, it might affect the rendering performance. Good default: 100
  • zoom: The zoom property allows you to zoom in and out of the scene. When you use a number lower than 1, you zoom out of the scene, and if you use a number higher than 1, you zoom in. Note that if you specify a negative value, the scene will be rendered upside down. Good default: 1

The following diagram gives a good overview of how these properties work together to determine what you see:

Figure 2.16 – Properties of the perspective camera

The fov property of the camera determines the horizontal FOV. Based on the aspect property, the vertical FOV is determined. The near property is used to determine the position of the near plane, and the far property determines the position of the far plane. The area between the near plane and the far plane will be rendered as follows:

Figure 2.17 – Far and near clip the rendered mesh

To configure the orthographic camera, we need to use other properties. The orthographic projection isn’t interested in which aspect ratio to use or what FOV we have of the scene, since all the objects are rendered at the same size. When you define an orthographic camera, you define the cuboid area that needs to be rendered. The properties of the orthographic camera reflect this, as follows:

  • left: This is described in the Three.js documentation as the camera frustum left plane. You should see this as the left-hand border of what will be rendered. If you set this value to -100, you won’t see any objects that are positioned farther than that on the left-hand side.
  • right: The right property works in a way similar to the left property, but this time, on the other side of the screen. Anything farther to the right won’t be rendered.
  • top: This is the top position to be rendered.
  • bottom: This is the bottom position to be rendered.
  • near: From this point, based on the position of the camera, the scene will be rendered.
  • far: To this point, based on the position of the camera, the scene will be rendered.
  • zoom: This allows you to zoom in and out of the scene. When you use a number lower than 1, you’ll zoom out of the scene; if you use a number higher than 1, you’ll zoom in. Note that if you specify a negative value, the scene will be rendered upside down. The default value is 1.

And all these properties can be summarized in the following diagram:

Figure 2.18 – Properties of the orthographic camera

And just like with the perspective camera, you can exactly define the area of the scene you want to render:

Figure 2.19 – Clipped area with an orthographic camera

In the previous section, we explained the different cameras supported by Three.js. You’ve learned how to configure them, and how you can use their properties to render different parts of the scene. What we didn’t show yet is how you can control what part of the scene a camera is looking at. We’ll explain that in the next section.

So far, you’ve seen how to create a camera and what the various arguments mean. In Chapter 1, Creating Your First 3D Scene with Three.js, you also saw that you need to position your camera somewhere in the scene and that the view from that camera is rendered. Normally, the camera is pointed to the center of the scene: position (0, 0, 0). We can, however, easily change what the camera is looking at, as follows:

camera.lookAt(new THREE.Vector3(x, y, z));

In the chapter2/cameras example, you can also specify the coordinates you want the camera to look at. Note that when you change lookAt in the OrthographicCamera settings, the cubes still stay the same size.

Figure 2.20 – Changed lookAt property for the orthographic camera

When you use the lookAt function, you point the camera at a specific position. You can also use this to make the camera follow an object around a scene. Since every THREE.Mesh object has a position that is a THREE.Vector3 object, you can use the lookAt function to point to a specific mesh in the scene. All you need to use is this: camera.lookAt(mesh.position). If you call this in the render loop, you’ll make the camera follow an object as it moves through a scene.

When looking at configuring the camera, having a menu where you can play around with the different settings can help a lot. Sometimes, though, you might want to exactly see the area that will be rendered by the camera. Three.js allows you to do this, by visualizing the frustum of the camera (the area that is shown by the camera). To do this, we simply add an additional camera to the scene and add a camera helper. To see this in action, open the chapter-2/debug-camera.html example:

Figure 2.21 – Show the frustum of the camera

In the preceding figure, you can see the outline of the frustum of a perspective camera. If you change the properties in the menu, you can see that the frustum changes as well. This frustum is visualized by adding the following:

const helper = new THREE.CameraHelper(camera);
scene.add(helper);
// in the render loop
helper.update();

We’ve also added a switchCamera button, which allows you to switch between the external camera looking in at the scene and the main camera in the scene. This provides a great way to get the correct settings for your camera:

Figure 2.22 – Switch between cameras

Switching cameras is really easy in Three.js. The only thing you need to do is tell Three.js you want to render the scene through a different camera.

We discussed a lot in this second introductory chapter. We showed the functions and properties of THREE.Scene and explained how you can use these properties to configure your main scene. We also showed you how to create geometries. You can either create them from scratch using a THREE.Buffergeometry object or use any of the built-in geometries Three.js provides. Finally, we showed you how to configure the two main cameras Three.js provides. THREE.PerspectiveCamera renders a scene using a real-world perspective, and THREE.OrthographicCamera provides the fake 3D effect often seen in games. We’ve also covered how geometries work in Three.js and you can now easily create your own geometries from the standard geometries provided by Three.js or by crafting them by hand.

In the next chapter, we’ll look at the various light sources that are available in Three.js. You’ll learn how the various light sources behave, how to create and configure them, and how they affect different materials.