100% found this document useful (2 votes)
292 views234 pages

Three.js User Manual and Guide

This document provides a table of contents for a Three.js tutorial. It outlines topics that will be covered, including installation of Three.js, creating a basic scene with a cube, adding responsiveness, debugging tools, different types of cameras and controls, lights and shadows, and various geometries.

Uploaded by

Diego Tz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
292 views234 pages

Three.js User Manual and Guide

This document provides a table of contents for a Three.js tutorial. It outlines topics that will be covered, including installation of Three.js, creating a basic scene with a cube, adding responsiveness, debugging tools, different types of cameras and controls, lights and shadows, and various geometries.

Uploaded by

Diego Tz
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

[Link] – Table of Contents Three.

js

[Link] – Table of Contents .............................................................................................. 1


Home ....................................................................................................................................... 5
Audience .................................................................................................................................. 5
Prerequisites ............................................................................................................................ 5

[Link] – Introduction...................................................................................................... 6
What is [Link]? ...................................................................................................................... 6
Why use [Link]? .................................................................................................................... 6
Browser Support ...................................................................................................................... 6

[Link] – Installation ....................................................................................................... 8


Download the complete [Link] project ................................................................................... 8
Use CDN links ........................................................................................................................... 8
Install the package of [Link]................................................................................................... 8

[Link] – Hello Cube App ............................................................................................... 10


The HTML............................................................................................................................... 10
The CSS .................................................................................................................................. 11
The JavaScript ........................................................................................................................ 11
The Scene............................................................................................................................... 12
The Camera ............................................................................................................................ 12
The Renderer ......................................................................................................................... 13
The Cube ................................................................................................................................ 13
Rendering the Scene ............................................................................................................... 13

[Link] – Renderer and Responsiveness ......................................................................... 17


Basic Functionality of a Scene ................................................................................................. 17
Adding an Object .................................................................................................................... 17
Removing an Object ............................................................................................................... 17
Children ................................................................................................................................. 17
Using name attribute .............................................................................................................. 23
Adding Fog to the scene.......................................................................................................... 23

1
[Link]

Using the override material property ...................................................................................... 24


Renderer ................................................................................................................................ 24

[Link] – Responsive Design .......................................................................................... 25


Automatically resize the output when the browser size changes.............................................. 25
Output ................................................................................................................................... 28
Anti-aliasing ........................................................................................................................... 28

[Link] – Debug and Stats ............................................................................................. 34


Using [Link]......................................................................................................................... 34
Installation ............................................................................................................................. 34
Usage ..................................................................................................................................... 34
Stats ...................................................................................................................................... 44
Installation ............................................................................................................................. 44
Functionality .......................................................................................................................... 44
How does it work?.................................................................................................................. 44
Usage ..................................................................................................................................... 44

[Link] – Cameras ......................................................................................................... 49


PerspectiveCamera................................................................................................................. 49
OrthographicCamera .............................................................................................................. 57
Making the Camera Follow an Object ...................................................................................... 65

[Link] – Controls .......................................................................................................... 67


Orbit Controls ........................................................................................................................ 67
Trackball Controls................................................................................................................... 72
Fly Controls ............................................................................................................................ 78
PointerLock Controls .............................................................................................................. 78

[Link] – Lights & Shadows ........................................................................................... 89


Ambient Light......................................................................................................................... 89
Directional Light ..................................................................................................................... 93
Casting Shadows .................................................................................................................... 94
Spotlight .............................................................................................................................. 100
Point Light ............................................................................................................................ 106
Hemisphere Light ................................................................................................................. 111

2
[Link]

[Link] – Geometries ................................................................................................... 117


Plane Geometry ................................................................................................................... 117
Circle Geometry ................................................................................................................... 122
Ring Geometry ..................................................................................................................... 126
Box Geometry ...................................................................................................................... 131
Sphere Geometry ................................................................................................................. 136
Cylinder Geometry ............................................................................................................... 141
Cone Geometry .................................................................................................................... 146
Torus Geometry ................................................................................................................... 151
TorusKnot Geometry ............................................................................................................ 155
Polyhedron Geometry .......................................................................................................... 159

[Link] – Materials ...................................................................................................... 172


MeshBasicMaterial ............................................................................................................... 172
MeshDepthMaterial ............................................................................................................. 172
MeshNormalMaterial ........................................................................................................... 176
MeshLambertMaterial .......................................................................................................... 180
MeshPhongMaterial ............................................................................................................. 180
MeshStandardMaterial ......................................................................................................... 180
MeshPhysicalMaterial .......................................................................................................... 180
Using Multiple Materials ...................................................................................................... 186

[Link] – Textures ....................................................................................................... 188


Basic Texture ........................................................................................................................ 188
Texture Mapping .................................................................................................................. 193

[Link] – Drawing Lines ............................................................................................... 203


Using BufferGeometry .......................................................................................................... 203

[Link] – Animations ................................................................................................... 212


Using [Link] in the [Link] project ..................................................................................... 213

[Link] – Creating Text ................................................................................................ 215


Draw Text to Canvas and Use as a Texture ............................................................................ 215
Using Text Geometry ............................................................................................................ 216

3
[Link]

[Link] – Loading 3D Models ....................................................................................... 228


OBJ Model Loader ................................................................................................................ 228
MTL Model Loader ............................................................................................................... 228
GLTF Model Loader............................................................................................................... 229
DRACO Loader ...................................................................................................................... 229
STL Model Loader ................................................................................................................. 230
Troubleshooting ................................................................................................................... 231
Asking for Help ..................................................................................................................... 231

[Link] – Libraries and Plugins ..................................................................................... 232

4
[Link]

Home
[Link] is an open-source JavaScript library that you can use to create dynamic and interactive
websites with 2D and 3D graphics. With [Link], you can render 3D graphics directly inside the
browser. You can do fantastic stuff using [Link] by adding animations or logic and even turning
your website into a game. Ricardo Cabello (or mrdoob in GitHub) released [Link] in 2010 and
maintained a great open-source community.

Audience
This tutorial is for anyone who already knows JavaScript and wants to create 3D graphics that run
in any browser. This tutorial makes you comfortable in getting started with [Link] and WebGL.

Prerequisites
Creating 3D applications that run in a browser falls at the intersection of web development and
computer graphics. You don’t need to know anything about computer graphics or advanced math;
all that is required is a general understanding of HTML, CSS, and JavaScript. If you are just getting
started with JavaScript, I recommend completing this tutorial before proceeding with this one.

5
[Link] – Introduction [Link]

All modern browsers became more powerful and more accessible directly using JavaScript. They
have adopted WebGL (Web Graphics Library), a JavaScript API, which allows you to render high-
performance interactive 3D and 2D graphics within any compatible web browser using the
capabilities of the GPU (Graphics Processing Unit).

But WebGL is a very low-level system that only draws basic objects like point, square, and line.
However, programming WebGL directly from JavaScript is a very complex and verbose process.
You need to know the inner details of WebGL and learn a complex shader language to get the
most out of WebGL. Here comes [Link] to make your life easy.

What is [Link]?
[Link] is an open-source, lightweight, cross-browser, general-purpose JavaScript library.
[Link] uses WebGL behind the scenes, so you can use it to render Graphics on an HTML
<canvas> element in the browser. Since [Link] uses JavaScript, you can interact with other web
page elements, add animations and interactions, and even create a game with some logic.

Why use [Link]?


The following features make [Link] an excellent library to use.
● You can create complex 3D graphics by just using JavaScript.
● You can create Virtual Reality (VR) and Augmented Reality (AR) scenes inside the
browser.
● Since it uses WebGL, it has cross-browser support. Many browsers support it.
● You can add various materials, textures and animate 3D objects.
● You can also load and work on objects from other 3D modeling software.
With a couple of lines of JavaScript and simple logic, you can create anything, from high-
performance interactive 3D models to photorealistic real-time scenes.
These are some excellent websites created using [Link]:
● Moments of Happiness
● Garden Eight
● Interland
● Under Neon Lights
You can find many other examples on the official website of [Link].

Browser Support
All modern browsers on desktop, as well as on mobile, currently support WebGL. The only browser
where you have to take care of is the mobile Opera Mini browser. For IE 10 and older, there is the

6
[Link]

IEWebGL plugin, which you can get from [Link] You can find detailed
information about the WebGL browser support here.
Once you understand what [Link] is, you can continue to the next chapter about setting up a
project to start working with [Link].

7
[Link] – Installation [Link]

There are many ways to include [Link] in your project. You can use any of these following
methods to get started using [Link]. Then open your favorite code editor and get going.

Download the complete [Link] project


Download the complete [Link] project into your system. You can download it here or from
GitHub. Extract the [Link] file and look inside the build folder. You can find two
[Link], [Link], which is just a minified version. Add any of these two files into your
project folder and link them to your HTML file. Now you are good to use [Link] in your project.
Note: We recommend using the minified version as it loads faster.
Insert the following <script> tag into the <head> element of your HTML with a path to the
[Link] file.

<script src='/path/to/[Link]'></script>

Use CDN links


You can link the files from a CDN (Content Delivery Network), a remote site dedicated to hosting
files so that you can use them online. You can use any of these websites:
● [Link]
● [Link]
Insert any of the following <script> tags into the <head> element of your HTML.

<script
src="[Link]
ript>

OR

<script
src="[Link]
>

Install the package of [Link]


[Link] is also available as a package on NPM. If you have [Link] set up on your computer, you
can install it using npm or yarn.

npm install three

or

yarn add three

8
[Link]

Then, you can import [Link] from the [Link] file into your JavaScript file.

import * as THREE from 'three'

You can use [Link] along with any JavaScript framework like React, Angular, Vue.
Once you finish setting up your project, let's start creating.

9
[Link] – Hello Cube App [Link]

Like any other programming language, let’s start learning [Link] by creating "Hello cube!" app.

The HTML
/[Link]
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>[Link] - Hello cube</title>
<style>
/* Our CSS goes here */
</style>
<script
src="[Link]
ript>
</head>

<body>
<div id="threejs-container">
<!-- Our output to be rendered here -->
</div>

<script type="module">
// our JavaScript code goes here
</script>
</body>
</html>

As you can see, it’s just a simple HTML file with [Link] CDN.

10
[Link]

The CSS
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

html,
body {
height: 100vh;
width: 100vw;
}

#threejs-container{
position: block;
width: 100%;
height: 100%;
}
</style>

The above CSS is just the basic styling of the HTML page. The threejs-container takes up the
whole screen.

The JavaScript
This is where our [Link] app comes into life. The code below renders a single cube in the middle
of the screen. All these codes will go into the empty <script> tag in the HTML.

const width = [Link]


const height = [Link]
// Scene
const scene = new [Link]()
[Link] = new [Link]('#00b140')

// Camera
const fov = 45 // AKA Field of View

11
[Link]

const aspect = [Link] / [Link]


const near = 0.1 // the near clipping plane
const far = 100 // the far clipping plane

const camera = new PerspectiveCamera(fov, aspect, near, far)


[Link](0, 0, 10)

// Renderer
const renderer = new [Link]()
[Link]([Link], [Link])
[Link]([Link]([Link], 2))

// Creating a cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({ wireframe: true })
const cube = new [Link](geometry, material)
[Link](cube)

// Rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)

Let’s discuss the code one step at a time, and then you can get more information about each
element in the upcoming chapters. The first thing we need to do is to create a scene, a camera,
and a renderer. These are the essential components that make up every [Link] app.

The Scene
const scene = new [Link]()
[Link] = new [Link]('#262626')

The scene serves as the container for everything we can see on the screen, without a
[Link] object, [Link] cannot render anything. The background color is dark gray so that
we can see the cube.

The Camera
const camera = new PerspectiveCamera(fov, aspect, near, far)
[Link](0, 0, 10)

12
[Link]

The camera object defines what we’ll see when we render a scene. There are not many but
different types of cameras, but for this example, you’ll use a PerspectiveCamera, which matches
the way our eyes see the world.

The Renderer
const renderer = new [Link]()
[Link]([Link], [Link])

The renderer object is responsible for calculating what the scene looks like in the browser, based
on the camera. There are different types of renderers, but we mainly use WebGLRenderer since
most browsers support WebGL.
In addition to creating the renderer instance, we also need to set the size at which we want it to
render our app. It's a good idea to use the width and height of the area we want to fill with our app
- in this case, the width and height of the browser window.

The Cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0xffffff,
wireframe: true,
})
const cube = new [Link](geometry, material)
[Link](cube)

The above code creates a simple cube at the center of the screen. We can make any object using
[Link]. The Mesh takes two objects, geometry and material. The geometry of a mesh
defines its shape, and materials determine the surface properties of objects.
To create a cube, we need BoxGeometry and a primary material (MeshBasicMaterial) with the
color 0xffffff. If the wireframe property is set to true, it tells [Link] to show us a wireframe
and not a solid object.

Rendering the Scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)

Last but not least, we add the renderer element to our HTML document. The renderer uses an
<canvas> element to display the scene to us. In this case, the renderer appends the <canvas>
element to the reference container in the HTML.

13
[Link]

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] – Hello cube</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
overflow: hidden;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Hello Cube App
// Your first [Link] application

14
[Link]

// sizes
const width = [Link]
const height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0xffffff,
wireframe: true
})
const cube = new [Link](geometry, material)
[Link](cube)

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
</script>
</body>
</html>

15
[Link]

Output
The output looks like this if everything is working correctly. Play around with the code to get a
better understanding of how it works.

You have now completed creating your first [Link] application. Let's go ahead and add more
beauty to the app.

16
[Link] – Renderer and Responsiveness [Link]

Basic Functionality of a Scene


You know that Scene is a container for the camera, lights, and objects we want to render on the
screen. Let’s look at some basic functionality of the Scene object:

Adding an Object
The function add(object) is used to an object to the scene.

const scene = [Link]()


[Link](cube) // adds the cube
[Link](sphere) // adds a sphere

Removing an Object
The function remove(object) removes an object from the scene.

[Link](cube) // removes the last added cube


[Link](sphere) // removes a sphere

Children
In the [Link] return an array of all the objects in the scene, including the camera and
lights.

[Link]([Link]) // outputs all the objects in the scene


[Link]([Link]) // outputs number of elements on the
scene

Note: We can give a name to any object using its name attribute. A name is handy for debugging
purposes but can also directly access an object from your scene.

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />

17
[Link]

<meta http-equiv="X-UA-Compatible" content="ie=edge" />


<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] – The scene</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
background-color: #262626;
overflow: hidden;
}
#btn-conatiner {
position: absolute;
top: 0;
left: 0;
height: 10vh;
width: 100%;
}
@media screen and (max-width:600px){
#btn-container{
display: flex;
flex-direction: column;
}
}
.btn {
padding: 5px 15px;
margin: 5px 15px;
font-weight: bold;
text-transform: uppercase;

18
[Link]

}
.add {
color: green;
}
.rem {
color: red;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="btn-conatiner">
<button class="btn add">Add Cube</button>
<button class="btn rem">Remove Cube</button>
</div>
<div id="threejs-container"></div>
<script type="module">
// Experimenting with different methods of scene
// add, remove, children, getElementById

// sizes
let width = [Link]
let height = [Link]

const gui = new [Link]()

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

19
[Link]

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)

const light = new [Link](0xffffff, 0.5)


[Link](-10, 10, -10)

// for shadow
[Link] = true
[Link] = 1024
[Link] = 1024
[Link] = 0.1
[Link] = 1000
[Link](light)

// camera
const camera = new [Link](45, width / height, 0.1, 1000)
[Link](0, 10, 40)
[Link](0, 0, 0)
[Link]([Link], 'z', 10, 200, 1).name('camera-z')

// plane
const planeGeometry = new [Link](100, 100)
const plane = new [Link](
planeGeometry,
new [Link]({ color: 0xffffff, side: [Link] })
)
[Link]([Link] / 2)
[Link].y = -1.75
[Link] = true
[Link](plane)

// [Link]
function addCube() {
const cubeSize = [Link]([Link]() * 3)
const cubeGeometry = new [Link](cubeSize, cubeSize, cubeSize)

20
[Link]

const cubeMaterial = new [Link]({


color: [Link]() * 0xffffff
})
const cube = new [Link](cubeGeometry, cubeMaterial)
[Link] = true
[Link] = 'cube-' + [Link]
[Link].x = -30 + [Link]([Link]() * 50)
[Link].y = [Link]([Link]() * 5)
[Link].z = -20 + [Link]([Link]() * 50)
[Link](cube)
}

const add = [Link]('.add')


[Link]('click', () => {
addCube()
[Link]('cube added')
})

// [Link]
function removeCube() {
const allChildren = [Link]
const lastObject = allChildren[[Link] - 1]
if ([Link]) {
[Link](lastObject)
}
}

const remove = [Link]('.rem')


[Link]('click', () => {
removeCube()
[Link]('cube removed')
})

// [Link]
[Link]([Link])

// responsiveness

21
[Link]

[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)
[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Open your console to see the elements on the scene.

22
[Link]

Using name attribute


The function [Link](name) directly returns the object, by specific name, from
the scene.
You can also add another argument - recursive.

[Link](name, recursive)

If you set the recursive argument to true, [Link] will search through the complete tree of objects
to find the thing with the specified name.

Adding Fog to the scene


This property allows you to set the fog for the scene. The fog renders a haze that hides faraway
objects.

[Link] = new [Link](0xffffff, 0.015, 100)

This line of code defines a white fog (0xffffff). You can use the preceding two properties to tune
how the mist appears. The 0.015 value sets the near property, and the 100 value sets the far
property. With these properties, you can determine where the fog starts and how fast it gets denser.
With the [Link] object, the fog increases linearly. There is also a different way to set the
mist for the scene; for this, use the following definition:

[Link] = 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). It's best to experiment a bit with these properties to get the effect you want.

23
[Link]

Using the override material property


The overrideMaterial property forces all the objects in the scene to use the same material.

[Link] = new [Link]({ color: 0xffffff })

Here, all the objects on the scene of the same material, i.e., MeshLambertMaterial.

Note: [Link] is a structure that is sometimes also called a Scenegraph. A scene graph
is a structure that can hold all the necessary information of a graphical scene. In [Link], this
means that [Link] contains all the objects, lights, and other objects needed for rendering.

Renderer
The renderer uses the camera and the information from the scene to draw the output on the screen,
i.e., <canvas> element.

In the Hello cube app, we used the WebGLRenderer. Some other renderers are available, but the
WebGLRenderer is by far the most powerful renderer available and usually the only one you need.
Note: There is a canvas-based renderer, a CSS-based renderer, and an SVG-based one. Even
though they work and can render simple scenes, I wouldn’t recommend using them. They are not
being developed actively, very CPU-intensive, and lack features such as good material support
and shadows.

24
[Link] – Responsive Design [Link]

On resizing the screen, you can observe that the scene is not responsive. Making a web page
responsive generally refers to the page displaying well on different sized displays from desktops
to tablets to phones. In this chapter, you can see how to solve some fundamental problems of your
[Link] app.

Automatically resize the output when the browser size changes


When you resize the browser, we have to notify the [Link] to know how wide the <canvas>
element should be. For the camera, we need to update the aspect property, which holds the aspect
ratio of the screen, and for the renderer, we need to change its size.

[Link]('resize', () => {
// update display width and height
width = [Link]
height = [Link]

// update camera aspect


[Link] = width / height
[Link]()

// update renderer
[Link](width, height)
[Link]([Link]([Link], 2))
[Link](scene, camera)
})

The above code gives responsiveness to your [Link] project.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] – Resizing browser</title>

25
[Link]

<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Adding responsiveness for [Link] app

// sizes
let width = [Link]
let height = [Link]

const gui = new [Link]()


// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

26
[Link]

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0xffffff,
wireframe: true
})
const cube = new [Link](geometry, material)
[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

27
[Link]

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output
When you execute the code, it will produce the following output:

Now, resize the browser. Due to the responsive design, the object will always reposition itself at
the center of the browser.

Anti-aliasing
The aliasing effect is the appearance of jagged edges or "jaggies" (also known as stair-stepped
lines) on edges and objects (rendered using pixels).

28
[Link]

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Anti-aliasing</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {

29
[Link]

height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Adding anti-aliasing to [Link] app for removing jaggies

// sizes
let width = [Link]
let height = [Link]

const gui = new [Link]()

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0xffffff,

30
[Link]

wireframe: true
})
const cube = new [Link](geometry, material)
[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer - anti-aliasing
const renderer = new [Link]({ antialias: true })
[Link] = true
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()

31
[Link]

</script>
</body>
</html>

Aliasing in our Hello cube app looks like this.

We can turn on anti-aliasing by setting antialias property of the WebGLRenderer to true. By


default, it is false. Here, we set the antialias parameter to true:

const renderer = new WebGLRenderer({ antialias: true })


[Link] = true

32
[Link]

After antialiasing, it looks smooth without jaggies like the one below.

The property physicallyCorrectLights tells [Link] whether to use physically correct lighting
mode. Default is false. Setting it to true helps increase the detail of the object.

33
[Link] – Debug and Stats [Link]

Using [Link]
It is hard to keep experimenting with the values of variables, like the cube’s position. In that case,
suppose until you get something you like. It's a kind of slow and overwhelming process. Luckily,
there is already a good solution available that integrates great with [Link], [Link]. It allows
you to create a fundamental user interface component that can change variables in your code.

Installation
To use [Link] in your project, download it here and add the <script> tag to the HTML file.

<script type='text/javascript' src='path/to/[Link]'></script>

Or you can use CDN, add the following <script> tag inside your HTML.

<script src="[Link]
gui/0.7.7/[Link]"></script>

If you are using [Link] in a node app, install the npm package - [Link] and import it into your
JavaScript file.

npm install [Link]

OR

yarn add [Link]


import * as dat from '[Link]'

Usage
First, you should initialize the object itself. It creates a widget and displays it on the screen top right
corner.

const gui = new [Link]()

Then, you can add the parameter you want to control and the variable. For example, the following
code is to control the y position of the cube.

[Link]([Link], 'y')

Try adding other position variables. Refer to this working code example.

34
[Link]

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Position GUI</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Adding UI to debug and experimenting different values

35
[Link]

// UI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0xffffff,
wireframe: true
})
[Link](material, 'wireframe')

const cube = new [Link](geometry, material)


[Link](cube)

[Link]([Link], 'x')
[Link]([Link], 'y')
[Link]([Link], 'z')

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

36
[Link]

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

37
[Link]

Output

You can customize the label displayed using the name attribute. To change the label on the variable
line, use .name("your label").

[Link]([Link], 'y').name('cube-y')

You can set up min/max limits and steps for getting the slider. The following line allow values
from 1 to 10, increasing the value by 1 at a time.

[Link]([Link], 'y').min(1).max(10).step(1)
// or
[Link]([Link], 'y', 1, 10, 1)

If there are many variables with the same name, you may find it difficult to differentiate among
them. In that case, you can add folders for every object. All the variables related to an object be
in one folder.

// creating a folder
const cube1 = [Link]('Cube 1')
[Link]([Link], 'y').min(1).max(10).step(1)
[Link]([Link], 'x').min(1).max(10).step(1)

38
[Link]

[Link]([Link], 'z').min(1).max(10).step(1)
// another folder
const cube2 = [Link]('Cube 2')
[Link]([Link], 'y').min(1).max(10).step(1)
[Link]([Link], 'x').min(1).max(10).step(1)
[Link]([Link], 'z').min(1).max(10).step(1)

Now, check the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - More variables</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>

39
[Link]

<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Adding folders to distinguish between variables

// controls
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0xffffff,
wireframe: true
})

const cubeColor = {
color: 0xffffff
}

40
[Link]

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link](cubeColor, 'color').onChange(() => {
// callback
[Link]([Link])
})
[Link]()

const cube = new [Link](geometry, material)


[Link](cube)

const cubeFolder = [Link]('Cube')

// for position
const posFolder = [Link]('position')
[Link]([Link], 'x', 0, 5, 0.1)
[Link]([Link], 'y', 0, 5, 0.1)
[Link]([Link], 'z', 0, 5, 0.1)
[Link]()

// for scale
const scaleFolder = [Link]('Scale')
[Link]([Link], 'x', 0, 5, 0.1).name('Width')
[Link]([Link], 'y', 0, 5, 0.1).name('Height')
[Link]([Link], 'z', 0, 5, 0.1).name('Depth')
[Link]()

[Link]()

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

41
[Link]

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

42
[Link]

Output

You can also add some callback functions. onChange is triggered once the value is changed.

[Link]([Link], 'y').onChange(function () {
// refresh based on the new value of y
[Link]([Link].y)
})

Let's see another example of changing color using [Link] and callbacks.

// parameter
const cubeColor = {
color: 0xff0000,
}
[Link](cubeColor, 'color').onChange(() => {
// callback
[Link]([Link])
})

The above callback onChange notifies [Link] to change the cube color when the color from
cubeColor changes.

43
[Link]

We are going to use this [Link] a lot from now. Make sure you get used to it by experimenting
with the "Hello Cube!" app.

Stats
Statistics play an important role in large-scale applications. Suppose you are creating a larger
[Link] project with many objects and animations. It is good to monitor the performance of the
code like fps (frames per second), memory allocated, etc. The creator of [Link] also created a
small JavaScript library, [Link], to monitor the rendering.

Installation
Like any other library, you can simply add it to your project in any of the three ways, as discussed
previously.
You can download it from GitHub and import it to your HTML page.
Or you can add the CDN link to the HTML page.

<script
src="[Link]
ipt>

If you're using a node app, install the npm package and import it into your project.

npm install [Link]

or

yarn add [Link]


import * as stats from '[Link]'

Functionality
You can monitor the following properties using [Link].
● FPS - Frames rendered in the last second (0).
● MS - Milliseconds needed to render a frame (1).
● MB - MBytes of allocated memory (2) (Run Chrome with --enable-precise-memory-
info)
● CUSTOM - you can define the thing you want to monitor—user-defined panel support (3).

How does it work?


If you're monitoring the frame rate, it counts how often the update was called within the last second
and shows that value. If you're tracking the render time, it just shows the time between calls and
the update function.

Usage
You can add this functionality to your code in a few simple steps.

44
[Link]

Create the stats object and add it to the HTML page using the DOM.

const stats = new Stats()


[Link](1) // 0: fps, 1: ms, 2: mb, 3+: custom
[Link]([Link])

Note: You can show the panel you want using showPanel(). By default, [Link] displays the fps
panel, and you can toggle between panels by clicking on the panel.
Select the code you want to monitor.

[Link]()

// monitored code goes here


// in our case the render function
[Link](scene, camera)
[Link]()

If you are using animations, you should update the stats whenever the frame is rendered.

function animate() {
requestAnimationFrame(render)
// our animations
[Link](scene, camera)
[Link]()
}

Check this working example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - [Link]</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;

45
[Link]

font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
<script src="[Link]
pt>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Adding stats panel to moniter application statistics

const gui = new [Link]()


const stats = new Stats()
//[Link](0)
//[Link](1)
[Link]([Link])

// width, height
let width = [Link]
let height = [Link]

// scene

46
[Link]

const scene = new [Link]()


[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)

// cube
const geometry = new [Link](1, 1, 1)
const material = new [Link]({
color: 0xffffff,
wireframe: true
})

const cube = new [Link](geometry, material)


[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

47
[Link]

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
[Link]()
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link]()
[Link](scene, camera)
[Link]()
animate()
</script>
</body>
</html>

Output

48
[Link] – Cameras [Link]

PerspectiveCamera
There are different cameras in [Link]. The most common camera and the one we've been using
is the PerspectiveCamera.

const camera = new [Link](fov, aspect, near, far)

The first attribute is the Field of View (FOV). FOV is the part of the scene that is visible on display
at any given moment. The value is in degrees. Humans have an almost 180-degree FOV. But
since a regular computer screen doesn’t fill our vision, a smaller value is often chosen. Generally,
for games, a FOV between 60 and 90 degrees is preferred.

Good default: 50

The second one is the Aspect ratio—the ratio between the horizontal and vertical sizes of the
area where we’re rendering the output.

Good default: [Link] / [Link]

The following two attributes are the near and far clipping plane. The camera renders the area
between the near plane and the far plane on the screen.
The near property defines by how close to the camera [Link] should render the scene. Usually,
we set this to a minimal value to directly render everything from the camera’s position.

Good default: 0.1

The far property defines how far the camera can see from the position of the camera. If we set
this too low, a 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: 1000

49
[Link]

Check out the following example and play around with variables.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Prespective camera</title>
<style>
html,
body {
margin: 0;
height: 100%;
}
#threejs-container {
width: 100%;
height: 100%;
display: block;
}

50
[Link]

.split {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
}
.split > div {
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<canvas id="threejs-container"></canvas>
<div class="split">
<div id="view1" tabindex="1"></div>
<div id="view2" tabindex="2"></div>
</div>

<script type="module">
// [Link] - Cameras - Prespective 2 views
// from [Link]
[Link]

import { OrbitControls } from "[Link]


ls/[Link]"

function main() {
const canvas = [Link]('#threejs-container')
const view1Elem = [Link]('#view1')
const view2Elem = [Link]('#view2')
const renderer = new [Link]({ canvas, antialias: true })

51
[Link]

const fov = 45
const aspect = 2 // the canvas default
const near = 5
const far = 100
const camera = new [Link](fov, aspect, near, far)
[Link](0, 10, 20)

const cameraHelper = new [Link](camera)

class MinMaxGUIHelper {
constructor(obj, minProp, maxProp, minDif) {
[Link] = obj
[Link] = minProp
[Link] = maxProp
[Link] = minDif
}
get min() {
return [Link][[Link]]
}
set min(v) {
[Link][[Link]] = v
[Link][[Link]] = [Link]([Link][[Link]], v + th
[Link])
}
get max() {
return [Link][[Link]]
}
set max(v) {
[Link][[Link]] = v
[Link] = [Link] // this will call the min setter
}
}

const gui = new [Link]()


[Link](camera, 'fov', 1, 180)
const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1)

52
[Link]

[Link](minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near')


[Link](minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far')

const controls = new OrbitControls(camera, view1Elem)


[Link](0, 5, 0)
[Link]()

const camera2 = new [Link](


60, // fov
2, // aspect
0.1, // near
500 // far
)
[Link](40, 10, 30)
[Link](0, 5, 0)

const controls2 = new OrbitControls(camera2, view2Elem)


[Link](0, 5, 0)
[Link]()

const scene = new [Link]()


[Link] = new [Link](0x262626)
[Link](cameraHelper)

{
const planeSize = 40

const planeGeo = new [Link](planeSize, planeSize)


const planeMat = new [Link]({
color: 0xffffff,
side: [Link]
})
const mesh = new [Link](planeGeo, planeMat)
[Link].x = [Link] * -0.5
[Link](mesh)
}
{

53
[Link]

const cubeSize = 4
const cubeGeo = new [Link](cubeSize, cubeSize, cubeSize)
const cubeMat = new [Link]({ color: 0x87ceeb })
const mesh = new [Link](cubeGeo, cubeMat)
[Link](cubeSize + 1, cubeSize / 2, 0)
[Link](mesh)
}
{
const sphereRadius = 3
const sphereWidthDivisions = 32
const sphereHeightDivisions = 16
const sphereGeo = new [Link](
sphereRadius,
sphereWidthDivisions,
sphereHeightDivisions
)
const sphereMat = new [Link]({ color: 0x71ba80 })
const mesh = new [Link](sphereGeo, sphereMat)
[Link](-sphereRadius - 1, sphereRadius + 2, 0)
[Link](mesh)
}

{
const color = 0xffffff
const intensity = 1
const light = new [Link](color, intensity)
[Link](0, 10, 5)
[Link](-5, 0, 0)
[Link](light)
[Link]([Link])

const light2 = new [Link](color, intensity)


[Link](0, 10, -5)
[Link](-5, 0, 0)
[Link](light2)
[Link]([Link])
}

54
[Link]

function resizeRendererToDisplaySize(renderer) {
const canvas = [Link]
const width = [Link]
const height = [Link]
const needResize = [Link] !== width || [Link] !== height
if (needResize) {
[Link](width, height, false)
}
return needResize
}

function setScissorForElement(elem) {
const canvasRect = [Link]()
const elemRect = [Link]()

// compute a canvas relative rectangle


const right = [Link]([Link], [Link]) - canvasR
[Link]
const left = [Link](0, [Link] - [Link])
const bottom = [Link]([Link], [Link]) - canv
[Link]
const top = [Link](0, [Link] - [Link])

const width = [Link]([Link], right - left)


const height = [Link]([Link], bottom - top)

// setup the scissor to only render to that part of the canvas


const positiveYUpBottom = [Link] - bottom
[Link](left, positiveYUpBottom, width, height)
[Link](left, positiveYUpBottom, width, height)

// return the aspect


return width / height
}

function render() {

55
[Link]

resizeRendererToDisplaySize(renderer)

// turn on the scissor


[Link](true)

// render the original view


{
const aspect = setScissorForElement(view1Elem)

// adjust the camera for this aspect


[Link] = aspect
[Link]()
[Link]()

// don't draw the camera helper in the original view


[Link] = false

[Link](0x262626)

// render
[Link](scene, camera)
}

// render from the 2nd camera


{
const aspect = setScissorForElement(view2Elem)

// adjust the camera for this aspect


[Link] = aspect
[Link]()

// draw the camera helper in the 2nd view


[Link] = true

[Link](0x262626)

[Link](scene, camera2)

56
[Link]

requestAnimationFrame(render)
}

requestAnimationFrame(render)
}

main()
</script>
</body>
</html>

Output

OrthographicCamera
The 2nd most common camera is the OrthographicCamera. It specifies a box with the settings
left, right top, bottom, near, and far. It represents three-dimensional objects in two dimensions.

const camera = new [Link](left, right, top, bottom, near,


far)

All the six attributes are the borders of the box; The camera renders only the objects inside the
box.
● left - Camera left the plane.
● right - Camera right plane.
● top - Camera top plane.

57
[Link]

● bottom - Camera bottom plane.


● near - Camera near plane.
● far - Camera far plane.

Check out the following example:

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Orthographic camera</title>
<style>
html,
body {
margin: 0;
height: 100%;
}
#threejs-container {
width: 100%;

58
[Link]

height: 100%;
display: block;
}
.split {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
display: flex;
}
.split > div {
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<canvas id="threejs-container"></canvas>
<div class="split">
<div id="view1" tabindex="1"></div>
<div id="view2" tabindex="2"></div>
</div>

<script type="module">
// [Link] - Cameras - Orthographic 2 views
// from [Link]
[Link]

import { OrbitControls } from "[Link]


ls/[Link]"

function main() {
const canvas = [Link]('#threejs-container')

59
[Link]

const view1Elem = [Link]('#view1')


const view2Elem = [Link]('#view2')
const renderer = new [Link]({ canvas, antialias: true })

const size = 1
const near = 5
const far = 50
const camera = new [Link](-size, size, size, -
size, near, far)
[Link] = 0.2
[Link](0, 10, 20)

const cameraHelper = new [Link](camera)

class MinMaxGUIHelper {
constructor(obj, minProp, maxProp, minDif) {
[Link] = obj
[Link] = minProp
[Link] = maxProp
[Link] = minDif
}
get min() {
return [Link][[Link]]
}
set min(v) {
[Link][[Link]] = v
[Link][[Link]] = [Link]([Link][[Link]], v + th
[Link])
}
get max() {
return [Link][[Link]]
}
set max(v) {
[Link][[Link]] = v
[Link] = [Link] // this will call the min setter
}
}

60
[Link]

const gui = new [Link]()


[Link](camera, 'zoom', 0.01, 1, 0.01).listen()
const minMaxGUIHelper = new MinMaxGUIHelper(camera, 'near', 'far', 0.1)
[Link](minMaxGUIHelper, 'min', 0.1, 50, 0.1).name('near')
[Link](minMaxGUIHelper, 'max', 0.1, 50, 0.1).name('far')

const controls = new OrbitControls(camera, view1Elem)


[Link](0, 5, 0)
[Link]()

const camera2 = new [Link](


60, // fov
2, // aspect
0.1, // near
500 // far
)
[Link](16, 28, 40)
[Link](0, 5, 0)

const controls2 = new OrbitControls(camera2, view2Elem)


[Link](0, 5, 0)
[Link]()

const scene = new [Link]()


[Link] = new [Link](0x262626)
[Link](cameraHelper)

{
const planeSize = 40

const planeGeo = new [Link](planeSize, planeSize)


const planeMat = new [Link]({
color: 0xffffff,
side: [Link]
})
const mesh = new [Link](planeGeo, planeMat)

61
[Link]

[Link].x = [Link] * -0.5


[Link](mesh)
}
{
const cubeSize = 4
const cubeGeo = new [Link](cubeSize, cubeSize, cubeSize)
const cubeMat = new [Link]({ color: 0x87ceeb })
const mesh = new [Link](cubeGeo, cubeMat)
[Link](cubeSize + 1, cubeSize / 2, 0)
[Link](mesh)
}
{
const sphereRadius = 3
const sphereWidthDivisions = 32
const sphereHeightDivisions = 16
const sphereGeo = new [Link](
sphereRadius,
sphereWidthDivisions,
sphereHeightDivisions
)
const sphereMat = new [Link]({ color: 0x71ba80 })
const mesh = new [Link](sphereGeo, sphereMat)
[Link](-sphereRadius - 1, sphereRadius + 2, 0)
[Link](mesh)
}

{
const color = 0xffffff
const intensity = 1
const light = new [Link](color, intensity)
[Link](0, 10, 5)
[Link](-5, 0, 0)
[Link](light)
[Link]([Link])

const light2 = new [Link](color, intensity)


[Link](0, 10, -5)

62
[Link]

[Link](-5, 0, 0)
[Link](light2)
[Link]([Link])
}

function resizeRendererToDisplaySize(renderer) {
const canvas = [Link]
const width = [Link]
const height = [Link]
const needResize = [Link] !== width || [Link] !== height
if (needResize) {
[Link](width, height, false)
}
return needResize
}

function setScissorForElement(elem) {
const canvasRect = [Link]()
const elemRect = [Link]()

// compute a canvas relative rectangle


const right = [Link]([Link], [Link]) - canvasR
[Link]
const left = [Link](0, [Link] - [Link])
const bottom = [Link]([Link], [Link]) - canv
[Link]
const top = [Link](0, [Link] - [Link])

const width = [Link]([Link], right - left)


const height = [Link]([Link], bottom - top)

// setup the scissor to only render to that part of the canvas


const positiveYUpBottom = [Link] - bottom
[Link](left, positiveYUpBottom, width, height)
[Link](left, positiveYUpBottom, width, height)

// return the aspect

63
[Link]

return width / height


}

function render() {
resizeRendererToDisplaySize(renderer)

// turn on the scissor


[Link](true)

// render the original view


{
const aspect = setScissorForElement(view1Elem)

// update the camera for this aspect


[Link] = -aspect
[Link] = aspect
[Link]()
[Link]()

// don't draw the camera helper in the original view


[Link] = false

[Link](0x262626)
[Link](scene, camera)
}

// render from the 2nd camera


{
const aspect = setScissorForElement(view2Elem)

// update the camera for this aspect


[Link] = aspect
[Link]()

// draw the camera helper in the 2nd view


[Link] = true

64
[Link]

[Link](0x262626)
[Link](scene, camera2)
}

requestAnimationFrame(render)
}

requestAnimationFrame(render)
}

main()
</script>
</body>
</html>

Output

Making the Camera Follow an Object


In the animation function, we use the [Link] function to point the camera to the position
function of the object. We do this in every frame that we render. It looks like the camera is exactly
following the object’s position.

function animate() {
const object = [Link]('sphere')
[Link](scene, camera)

65
[Link]

[Link]([Link])
requestAnimationFrame(render)
}

66
[Link] – Controls [Link]

You can move the camera around the scene using camera controls. [Link] has many camera
controls you can use to control the camera throughout a scene. You have to get the controls
separately from GitHub. The [Link] library does not include these.

Orbit Controls
Orbit controls allow the camera to orbit around the center of the scene. You can also provide a
target to move around. You can add Orbitcontrols in a few simple steps.

Create a new instance of the orbit controls and pass the camera.

const controls = new [Link](camera, [Link])

Update the controls for every frame. You can simply do it in your animation loop.

function animate() {
// any other animations
[Link]()
requestAnimationFrame(render)
}

Refer to this example for some basic settings.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Orbit Controls</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;

67
[Link]

}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>

</head>
<body>
<div id="container"></div>
<script type="module">
// Adding orbit controls to [Link] application
// In this example, autorotate is set to true, so the camera rotates a
round the cube

import { OrbitControls } from "[Link]


ls/[Link]"
// controls
const gui = new [Link]()
[Link]('start')

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

68
[Link]

[Link]([Link])

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link]([Link], [Link])
[Link] = true
[Link] = [Link]
[Link]([Link]([Link], 2))

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)

const light = new [Link](0xffffff, 0.5)


[Link](0, 10, 10)

// for shadow
[Link] = true
[Link] = 1024
[Link] = 1024
[Link] = 0.5
[Link] = 100
[Link](light)

// camera
const camera = new [Link](60, width / height, 0.1, 1000)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z', 10, 80, 1)
[Link]()

const controls = new OrbitControls(camera, [Link])


[Link] = true

const ocFolder = [Link]('Orbit Controls')


[Link](controls, 'enabled')
[Link](controls, 'enableZoom')

69
[Link]

[Link](controls, 'enableRotate')
[Link](controls, 'enablePan')
[Link](controls, 'autoRotate')
[Link](controls, 'autoRotateSpeed', 1, 100, 1)
[Link]()

// axes
const axesHelper = new [Link](20)
[Link](axesHelper)

// plane
const planeGeometry = new [Link](1000, 1000)
const plane = new [Link](
planeGeometry,
new [Link]({ color: 0xffffff, side: [Link] })
)
[Link](-[Link] / 2)
[Link].y = -1.75
[Link] = true
[Link](plane)

// cube
[Link]('cube')
const geometry = new [Link](2, 2, 2)
const matArray = [
new [Link]({ color: 0xff8b8b }),
new [Link]({ color: 0xf5ffa2 }),
new [Link]({ color: 0xb5dccd }),
new [Link]({ color: 0xaaffa2 }),
new [Link]({ color: 0x9fd1ff }),
new [Link]({ color: 0xffaef7 }),
]

const cube = new [Link](geometry, matArray)


[Link](0, 0.5, 0)
[Link]([Link] / 6)
[Link] = true

70
[Link]

[Link] = true
[Link]([Link])
[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// animation
function animate() {
requestAnimationFrame(animate)

//[Link].x += 0.005
//[Link].y += 0.01

[Link]()

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#container')
[Link]([Link])
[Link](scene, camera)
animate()
[Link]([Link])
</script>
</body>
</html>

71
[Link]

Output

There are many other settings to make your experience better. The code is well-documented; you
can refer the codes here.

Trackball Controls
TrackballControls is similar to Orbit controls. However, it does not maintain a constant camera up
vector. That means that the camera can orbit past its polar extremes. It won't flip to stay the right
side up. You can add it just like the previous one.

const controls = new [Link](camera, [Link])

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<title>[Link] - Trackball controls</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, user-scalable=no, minimum-
scale=1.0, maximum-scale=1.0"
/>
<style>
body {
background-color: #ccc;

72
[Link]

color: #000;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
a {
color: #f00;
}
#info {
position: absolute;
top: 0px;
width: 100%;
padding: 10px;
box-sizing: border-box;
text-align: center;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
user-select: none;
pointer-events: none;
z-index: 1; /* TODO Solve this in HTML */
}

a,
button,
input,
select {
pointer-events: auto;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
<script src="[Link]
pt>
</head>
<body>

73
[Link]

<div id="info">
<a href="[Link] target="_blank" rel="noopener">[Link]<
/a> - trackball
controls<br />
MOVE mouse &amp; press LEFT/A: rotate, MIDDLE/S: zoom, RIGHT/D: pan
</div>

<script type="module">
// Adding trackball controls
// You can rotate camera any direction you want using Trackball controls

import { TrackballControls } from '[Link]


ntrols/[Link]'

let perspectiveCamera, orthographicCamera, controls, scene, renderer, stats

const params = {
orthographicCamera: false
}

const frustumSize = 400

init()
animate()

function init() {
const aspect = [Link] / [Link]

perspectiveCamera = new [Link](60, aspect, 1, 1000)


[Link].z = 500

orthographicCamera = new [Link](


(frustumSize * aspect) / -2,
(frustumSize * aspect) / 2,
frustumSize / 2,
frustumSize / -2,
1,

74
[Link]

1000
)
[Link].z = 500

// world

scene = new [Link]()


[Link] = new [Link](0xcccccc)
[Link] = new THREE.FogExp2(0xcccccc, 0.002)

const geometry = new [Link](0, 10, 30, 4, 1)


const material = new [Link]({ color: 0xffffff, flat
Shading: true })

for (let i = 0; i < 500; i++) {


const mesh = new [Link](geometry, material)
[Link].x = ([Link]() - 0.5) * 1000
[Link].y = ([Link]() - 0.5) * 1000
[Link].z = ([Link]() - 0.5) * 1000
[Link]()
[Link] = false
[Link](mesh)
}

// lights

const dirLight1 = new [Link](0xffffff)


[Link](1, 1, 1)
[Link](dirLight1)

const dirLight2 = new [Link](0x002288)


[Link](-1, -1, -1)
[Link](dirLight2)

const ambientLight = new [Link](0x222222)


[Link](ambientLight)

75
[Link]

// renderer

renderer = new [Link]({ antialias: true })


[Link]([Link])
[Link]([Link], [Link])
[Link]([Link])

stats = new Stats()


[Link]([Link])

//

const gui = new [Link]()


gui
.add(params, 'orthographicCamera')
.name('use orthographic')
.onChange(function (value) {
[Link]()

createControls(value ? orthographicCamera : perspectiveCamera)


})

//

[Link]('resize', onWindowResize)

createControls(perspectiveCamera)
}

function createControls(camera) {
controls = new TrackballControls(camera, [Link])

[Link] = 1.0
[Link] = 1.2
[Link] = 0.8

[Link] = ['KeyA', 'KeyS', 'KeyD']

76
[Link]

function onWindowResize() {
const aspect = [Link] / [Link]

[Link] = aspect
[Link]()

[Link] = (-frustumSize * aspect) / 2


[Link] = (frustumSize * aspect) / 2
[Link] = frustumSize / 2
[Link] = -frustumSize / 2
[Link]()

[Link]([Link], [Link])

[Link]()
}

function animate() {
requestAnimationFrame(animate)

[Link]()

[Link]()

render()
}

function render() {
const camera = [Link] ? orthographicCamera : pers
pectiveCamera

[Link](scene, camera)
}
</script>
</body>

77
[Link]

</html>

Output

Fly Controls
These are flight simulator-like controls. Move and steer with the keyboard and the mouse. You can
arbitrarily transform the camera in 3D space without any limitations (e.g., focus on a specific target).

const controls = new [Link](camera, [Link])

PointerLock Controls
The PointerLockControls implements the inbuilt browsers Pointer Lock API. It allows you to
control the camera just like in a first-person in 3D games.

const controls = new PointerLockControls(camera, [Link])

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<title>[Link] - Pointerlock controls</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, user-scalable=no, minimum-
scale=1.0, maximum-scale=1.0"

78
[Link]

/>
<link type="text/css" rel="stylesheet" href="[Link]" />
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#blocker {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}

#instructions {
width: 100%;
height: 100%;

display: -webkit-box;
display: -moz-box;
display: box;

-webkit-box-orient: horizontal;
-moz-box-orient: horizontal;
box-orient: horizontal;

-webkit-box-pack: center;
-moz-box-pack: center;
box-pack: center;

-webkit-box-align: center;
-moz-box-align: center;
box-align: center;

color: #ffffff;
text-align: center;

79
[Link]

font-family: Arial;
font-size: 14px;
line-height: 24px;

cursor: pointer;
}
</style>
<script src="[Link]
[Link]"></script>
</head>
<body>
<div id="blocker">
<div id="instructions">
<span style="font-size: 36px">Click to play</span>
<br /><br />
Move: WASD<br />
Jump: SPACE<br />
Look: MOUSE
</div>
</div>

<script type="module">
// Adding pointer lock controls to [Link]
// You can move around the scene using mouse and keyboard

import { PointerLockControls } from '[Link]


controls/[Link]'

let camera, scene, renderer, controls

const objects = []

let raycaster

let moveForward = false


let moveBackward = false
let moveLeft = false

80
[Link]

let moveRight = false


let canJump = false

let prevTime = [Link]()


const velocity = new THREE.Vector3()
const direction = new THREE.Vector3()
const vertex = new THREE.Vector3()
const color = new [Link]()

init()
animate()

function init() {
camera = new [Link](75, [Link] / window.
innerHeight, 1, 1000)
[Link].y = 10

scene = new [Link]()


[Link] = new [Link](0xffffff)
[Link] = new [Link](0xffffff, 0, 750)

const light = new [Link](0xeeeeff, 0x777788, 0.75)


[Link](0.5, 1, 0.75)
[Link](light)

controls = new PointerLockControls(camera, [Link])

const blocker = [Link]('blocker')


const instructions = [Link]('instructions')

[Link]('click', function () {
[Link]()
})

[Link]('lock', function () {
[Link] = 'none'
[Link] = 'none'

81
[Link]

})

[Link]('unlock', function () {
[Link] = 'block'
[Link] = ''
})

[Link]([Link]())

const onKeyDown = function (event) {


switch ([Link]) {
case 'ArrowUp':
case 'KeyW':
moveForward = true
break

case 'ArrowLeft':
case 'KeyA':
moveLeft = true
break

case 'ArrowDown':
case 'KeyS':
moveBackward = true
break

case 'ArrowRight':
case 'KeyD':
moveRight = true
break

case 'Space':
if (canJump === true) velocity.y += 350
canJump = false
break
}
}

82
[Link]

const onKeyUp = function (event) {


switch ([Link]) {
case 'ArrowUp':
case 'KeyW':
moveForward = false
break

case 'ArrowLeft':
case 'KeyA':
moveLeft = false
break

case 'ArrowDown':
case 'KeyS':
moveBackward = false
break

case 'ArrowRight':
case 'KeyD':
moveRight = false
break
}
}

[Link]('keydown', onKeyDown)
[Link]('keyup', onKeyUp)

raycaster = new [Link](new THREE.Vector3(), new [Link]


r3(0, -1, 0), 0, 10)

// floor

let floorGeometry = new [Link](2000, 2000, 100, 100)


[Link](-[Link] / 2)

// vertex displacement

83
[Link]

let position = [Link]

for (let i = 0, l = [Link]; i < l; i++) {


[Link](position, i)

vertex.x += [Link]() * 20 - 10
vertex.y += [Link]() * 2
vertex.z += [Link]() * 20 - 10

[Link](i, vertex.x, vertex.y, vertex.z)


}

floorGeometry = [Link]() // ensure each face has


unique vertices

position = [Link]
const colorsFloor = []

for (let i = 0, l = [Link]; i < l; i++) {


[Link]([Link]() * 0.3 + 0.5, 0.75, [Link]() * 0.25
+ 0.75)
[Link](color.r, color.g, color.b)
}

[Link]('color', new THREE.Float32BufferAttribute


(colorsFloor, 3))

const floorMaterial = new [Link]({ vertexColors: true })

const floor = new [Link](floorGeometry, floorMaterial)


[Link](floor)

// objects

const boxGeometry = new [Link](20, 20, 20).toNonIndexed()

position = [Link]

84
[Link]

const colorsBox = []

for (let i = 0, l = [Link]; i < l; i++) {


[Link]([Link]() * 0.3 + 0.5, 0.75, [Link]() * 0.25 + 0.75)

[Link](color.r, color.g, color.b)


}

[Link]('color', new THREE.Float32BufferAttribute(c


olorsBox, 3))

for (let i = 0; i < 500; i++) {


const boxMaterial = new [Link]({
specular: 0xffffff,
flatShading: true,
vertexColors: true
})
[Link]([Link]() * 0.2 + 0.5, 0.75, [Link]
dom() * 0.25 + 0.75)

const box = new [Link](boxGeometry, boxMaterial)


[Link].x = [Link]([Link]() * 20 - 10) * 20
[Link].y = [Link]([Link]() * 20) * 20 + 10
[Link].z = [Link]([Link]() * 20 - 10) * 20

[Link](box)
[Link](box)
}

//

renderer = new [Link]({ antialias: true })


[Link]([Link])
[Link]([Link], [Link])
[Link]([Link])

//

85
[Link]

[Link]('resize', onWindowResize)
}

function onWindowResize() {
[Link] = [Link] / [Link]
[Link]()

[Link]([Link], [Link])
}

function animate() {
requestAnimationFrame(animate)

const time = [Link]()

if ([Link] === true) {


[Link]([Link]().position)
[Link].y -= 10

const intersections = [Link](objects)

const onObject = [Link] > 0

const delta = (time - prevTime) / 1000

velocity.x -= velocity.x * 10.0 * delta


velocity.z -= velocity.z * 10.0 * delta

velocity.y -= 9.8 * 100.0 * delta // 100.0 = mass

direction.z = Number(moveForward) - Number(moveBackward)


direction.x = Number(moveRight) - Number(moveLeft)
[Link]() // this ensures consistent movements in all directions

if (moveForward || moveBackward) velocity.z -= direction.z * 400.0 * delta

if (moveLeft || moveRight) velocity.x -= direction.x * 400.0 * delta

86
[Link]

if (onObject === true) {


velocity.y = [Link](0, velocity.y)
canJump = true
}

[Link](-velocity.x * delta)
[Link](-velocity.z * delta)

[Link]().position.y += velocity.y * delta // new behavior

if ([Link]().position.y < 10) {


velocity.y = 0
[Link]().position.y = 10

canJump = true
}
}

prevTime = time

[Link](scene, camera)
}
</script>
</body>
</html>

87
[Link]

Output

In this chapter, we have seen the most useful controls. Some developers are creating more useful
controls for [Link]. You can see some other controls here, well documented and easy to use.

88
[Link] – Lights & Shadows [Link]

Lights make the objects visible, similarly, in [Link] [Link] lights up the scene and makes
some things visible. Not all materials are affected by lighting. The MeshBasicMaterial and
MeshNormalMaterial are self-illuminating, so they don't need lighting to be visible within a scene.
However, most of the other materials do, the MeshLambertMaterial, MeshPhongMaterial,
MeshStandardMaterial, MeshPhysicalMaterial, and MeshToonMaterial. We'll discuss more
materials in further chapters. In this chapter, we'll focus on different types of lights in [Link].
Every light has color and intensity properties.

● color - (optional) hexadecimal color of the light. Default is 0xffffff (white).


● intensity - (optional) numeric value of the light's strength/intensity. Default is 1.

Ambient Light
It is the most basic light, which illuminates the whole scene equally. Light is spread equally in all
directions and distances, so it cannot cast shadows. Ambient light affects all lit objects in the scene
equally, and it adds color to the object's material.

const light = [Link](color, intensity)

Play around with the code in the following example with different colors and intensities.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - AmbientLight</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

89
[Link]

html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="container"></div>
<script type="module">
// Adding Ambient to the scene
// without this light you cannot see the color of the cube

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)

90
[Link]

// lights
const light = new [Link](0xffffff, 1)
[Link](light)

// light controls
const lightColor = {
color: [Link]()
}
const lightFolder = [Link]('Ambient Light')
[Link](lightColor, 'color').onChange(() => {
[Link]([Link])
})
[Link](light, 'intensity', 0, 1, 0.01)
[Link]()

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0xffffff,
wireframe: true
})
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[Link]()

const cube = new [Link](geometry, material)


[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)

91
[Link]

})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

92
[Link]

Output

Directional Light
Directional light comes from a specific point and is emitted directly from far away to the target. All
the light rays it sends out are parallel to each other. An excellent example of this is the sun.

const light = [Link](color, intensity)


[Link](2, 3, 4)

93
[Link]

Casting Shadows
The light that is coming from a specific direction can cast shadows. First, we should make the
scene ready for casting shadows.

Step - 1
We should first tell the renderer that we want to enable shadows. Casting shadows is an expensive
operation. WebGLRenderer only supports this functionality. It uses Shadow mapping, a technique
specific to WebGL, performed directly on the GPU.

[Link] = true

The above line of code tells the renderer to cast shadows in the scene.
Note: [Link], by default, uses shadow maps. Shadow map works for light that casts shadows.
The scene renders all objects marked to cast shadows from the point of view of the light.
If your shadow looks a bit blocky around its edges, it means the shadow map is too small. To
increase the shadow map size, you can define shadowMapHeight and shadowMapWidht properties
for the light. Alternatively, you can also try to change the shadowMapType property of
WebGLRenderer. You can set this to [Link], [Link], or
[Link].

// to antialias the shadow

94
[Link]

[Link] = [Link]

// or

[Link] = 2048
[Link] = 2048

Step - 2
You should configure objects to cast shadows. You can inform [Link] which objects can cast
shadows and which objects can receive shadows.

[Link] = true
[Link] = true

Step - 3
All the above steps are the same for every light. The next step is to set up the shadow-related
properties.

[Link] = true
[Link] = 10
[Link] = 100
[Link] = -50
[Link] = 50
[Link] = 50
[Link] = -50

The first property, castShadow, tells [Link] that this light casts shadows. As casting shadows is
an expensive operation, we need to define the area where shadows can appear. You can do it
with the [Link], [Link], and [Link], etc. properties.
With the above properties, we create a box-like area where [Link] render shadows.
Explore more in this example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Directional Light</title>

95
[Link]

<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="container"></div>
<script type="module">
// Adding directional light to the scene
// The lights falls from the light only in one direction.
// You can see the position of light using helpers provided in Three.j
s for debugging purposes

// GUI
const gui = new [Link]()

// sizes
let width = [Link]

96
[Link]

let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 1000)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z', 10, 80, 1)
[Link]()

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)
const light = new [Link]()
[Link](2.5, 2, 2)
[Link] = true
[Link] = 512
[Link] = 512
[Link] = 0.5
[Link] = 100
[Link](light)
const helper = new [Link](light)
[Link](helper)

// light controls
const lightColor = {
color: [Link]()
}
const lightFolder = [Link]('Directional Light')
[Link](lightColor, 'color').onChange(() => {
[Link]([Link])
})
[Link](light, 'intensity', 0, 1, 0.01)
[Link]()

97
[Link]

const directionalLightFolder = [Link]('Position of Light')


[Link]([Link], 'x', -10, 10, 0.1)
[Link]([Link], 'y', -10, 10, 0.1)
[Link]([Link], 'z', -10, 10, 0.1)
[Link]()

// plane
const planeGeometry = new [Link](100, 20)
const plane = new [Link](planeGeometry, new [Link]
l({ color: 0xffffff }))
[Link](-[Link] / 2)
[Link].y = -1.75
[Link] = true
[Link](plane)

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0x87ceeb
})
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[Link]()

const cube = new [Link](geometry, material)


[Link](0, 0.5, 0)
[Link] = true
[Link] = true
[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

98
[Link]

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link]([Link], [Link])
[Link] = true
[Link] = [Link]
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

99
[Link]

Output

Spotlight
It is another kind of light that comes from a specific direction in the shape of the cone.
● distance - Maximum range of the light. Default is 0 (no limit).
● angle - Maximum angle of light dispersion from its direction whose upper bound is
[Link]/2.
● penumbra - Percent of the spotlight cone attenuates due to penumbra. It takes values
between zero and 1. Default is 0.
● decay - The amount the light dims along with the distance of the light.

100
[Link]

const light = new [Link](color, intensity)


[Link](1, 10, 10)

[Link] = true
[Link] = 5
[Link] = 400
[Link] = 30

The [Link], [Link], and [Link] properties define the


area where shadows can appear.
Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - SpotLight</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;

101
[Link]

}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="container"></div>
<script type="module">
// Adding spotlight in [Link]
// You can control the properties of light using the GUI
// You can see the position and the cone of light in this example

// GUI
const gui = new [Link]()

// sizes
const width = [Link]
const height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)
[Link]([Link])

// camera
const camera = new [Link](60, width / height, 0.1, 1000)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z', 10, 80, 1)
[Link]()

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)
const light = new [Link]()

102
[Link]

[Link](0, 5, 0)

// for shadow
[Link] = true
[Link] = 1024
[Link] = 1024
[Link] = 0.5
[Link] = 100
[Link](light)

const helper = new [Link](light)


[Link](helper)

// light controls
const lightColor = {
color: [Link]()
}
const lightFolder = [Link]('Light')
[Link](lightColor, 'color').onChange(() => {
[Link]([Link])
})
[Link](light, 'intensity', 0, 1, 0.01)
[Link]()

const spotLightFolder = [Link]('SpotLight')


[Link](light, 'distance', 0, 100, 0.01)
[Link](light, 'decay', 0, 4, 0.1)
[Link](light, 'angle', 0, 1, 0.1)
[Link](light, 'penumbra', 0, 1, 0.1)
[Link]([Link], 'x', -50, 50, 1)
[Link]([Link], 'y', -50, 50, 1)
[Link]([Link], 'z', -50, 50, 1)
[Link]()

// plane
const planeGeometry = new [Link](100, 100)

103
[Link]

const plane = new [Link](planeGeometry, new [Link]


l({ color: 0xffffff }))
[Link](-[Link] / 2)
[Link].y = -1.75
[Link] = true
[Link](plane)

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0x87ceeb
})
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[Link]()

const cube = new [Link](geometry, material)


[Link](0, 0.5, 0)
[Link] = true
[Link] = true
[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link]([Link], [Link])
[Link] = true

104
[Link]

[Link] = [Link]
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#container')
[Link]([Link])
[Link](scene, camera)

animate()
</script>
</body>
</html>

Output

105
[Link]

Point Light
The point light is a light source that emits light in all directions from a single point. It is very similar
to the light bulb in the ordinary world. It can cast shadows because it is a type of directional light.

const light = new [Link](color, intensity, distance, decay)

[Link] = true
[Link] = 0.5 // default
[Link] = 500 // default

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>

106
[Link]

<meta charset="UTF-8" />


<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - PointLight</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="container"></div>
<script type="module">
// Adding point light to [Link] scene
// It is like a small sun, which emits light from a point in all directions

// GUI
const gui = new [Link]()

107
[Link]

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)
[Link]([Link])

// camera
const camera = new [Link](60, width / height, 0.1, 1000)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z', 10, 80, 1)
[Link]()

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)

const light = new [Link]()


[Link](light)

const helper = new [Link](light)


[Link](helper)
// for shadow
[Link] = true
[Link] = 1024
[Link] = 1024
[Link] = 0.5
[Link] = 100
[Link](light)

// light controls
const lightColor = {
color: [Link]()
}

108
[Link]

const lightFolder = [Link]('Light')


[Link](lightColor, 'color').onChange(() => {
[Link]([Link])
})
[Link](light, 'intensity', 0, 1, 0.01)
[Link]()

const pointLightFolder = [Link]('[Link]')


[Link](light, 'distance', 0, 100, 0.01)
[Link](light, 'decay', 0, 4, 0.1)
[Link]([Link], 'x', -50, 50, 0.01)
[Link]([Link], 'y', -50, 50, 0.01)
[Link]([Link], 'z', -50, 50, 0.01)
[Link]()

// plane
const planeGeometry = new [Link](100, 20)
const plane = new [Link](planeGeometry, new [Link]
l({ color: 0xffffff }))
[Link](-[Link] / 2)
[Link].y = -2.5
[Link] = true
[Link](plane)

// torus
const geometry = new [Link](1.5, 0.5, 20, 50)
const material = new [Link]({
color: 0x87ceeb
})
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[Link]()

const torus = new [Link](geometry, material)


[Link] = true
[Link] = true
[Link](torus)

109
[Link]

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link]([Link], [Link])
[Link] = true
[Link] = [Link]
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#container')
[Link]([Link])
[Link](scene, camera)

animate()
</script>
</body>

110
[Link]

</html>

Output

Hemisphere Light
It is a special light for creating natural lighting. If you look at the lighting outside, you'll see that the
lights don't come from a single direction. Earth reflects part of the sunlight, and the atmosphere
scatters the other parts. The result is a very soft light coming from lots of directions. In [Link],
we can create something similar using [Link].

const light = new [Link](color, groundColor, intensity)

The first argument sets the color of the sky, and the second color sets the color reflected from the
floor. And the last argument is its intensity.
It is often used along with some other lights, which can cast shadows for the best outdoor lighting
effect.
Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - HemisphereLight</title>
<style>

111
[Link]

* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="container"></div>
<script type="module">
// Adding hemisphere light in [Link]
// It gives the lighting of physical world

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene

112
[Link]

const scene = new [Link]()


[Link] = new [Link](0x262626)

// camera
const camera = new [Link](60, width / height, 0.1, 1000)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z', 10, 80, 1)
[Link]()

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)

const skyColor = 0xb1e1ff // light blue


const groundColor = 0xb97a20 // brownish
const light = new [Link](skyColor, groundColor)
[Link](0, 5, 0)
[Link](light)

const helper = new [Link](light, 5)


[Link](helper)

// light controls
const lightColor = {
color: [Link](),
groundColor: [Link]()
}
const lightFolder = [Link]('Light')
lightFolder
.addColor(lightColor, 'color')
.name('Light Color')
.onChange(() => {
[Link]([Link])
})
[Link](light, 'intensity', 0, 1, 0.01)
[Link]()

113
[Link]

const hemisphereLightFolder = [Link]('Hemisphere Light')


hemisphereLightFolder
.addColor(lightColor, 'groundColor')
.name('ground Color')
.onChange(() => {
[Link]([Link])
})
[Link]([Link], 'x', -100, 100, 0.01)
[Link]([Link], 'y', -100, 100, 0.01)
[Link]([Link], 'z', -100, 100, 0.01)
[Link]()

// cube
[Link]('cube')
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0x87ceeb
})
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[Link]()

const cube = new [Link](geometry, material)


[Link](0, 0.5, 0)
[Link] = true
[Link] = true
[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])

114
[Link]

[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link]([Link], [Link])
[Link] = true
[Link] = [Link]
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

115
[Link]

Output

116
[Link] – Geometries [Link]

Geometries are used to create and define shapes in [Link]. [Link] has many types of built-in
geometries, both 2D and 3D.
In this chapter, we'll discuss basic built-in geometries. We’ll first look at the 2D geometries, and
after that, we’ll explore all the basic 3D geometries that are available.

Plane Geometry
The [Link] creates a simple 2D rectangle. It takes four arguments, the width,
height is mandatory, and the widthSegments, heightSegments are optional.

● width - The width of the rectangle.


● height - The height of the rectangle.
● widthSegments - The number of segments the width should be divided. This defaults to
1.
● heightSegments - The number of segments the height should be divided. This defaults
to 1.

const plane = new [Link](


width, height,
widthSegments, heightSegments
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Plane</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;

117
[Link]

font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Plane geometry
// A rotating 2d rectangle in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera

118
[Link]

const camera = new [Link](30, width / height, 0.1, 100)


[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// Light
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.2)

[Link].x = 2
[Link].y = 3
[Link].z = 4

[Link](pointLight)

// plane
const geometry = new [Link](1, 1)
const material = new [Link]({
color: 0xffffff,
wireframe: true,
side: [Link]
})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const plane = new [Link](geometry, material)


[Link](plane)

// experimenting plane properties


const planeProps = {
width: 1,
height: 1,

119
[Link]

widthSegments: 1,
heightSegments: 1
}
const props = [Link]('Properties')
props
.add(planeProps, 'width', 1, 30)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](planeProps, 'height', 1, 30).step(1).onChange(redraw)
[Link](planeProps, 'widthSegments', 1, 30).step(1).onChange(redraw)
[Link](planeProps, 'heightSegments', 1, 30).step(1).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer

120
[Link]

const renderer = new THREE.WebGL1Renderer()


[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

121
[Link]

Circle Geometry
The [Link] creates a simple 2D circle. It takes four arguments, and all are
optional.
● radius - The radius of a circle defines its size. The default value is 1.
● segments - the number of faces used to create the circle. The default value is 8. The
more segments, the smoother circle is.
● thetaStart - The position from which to start drawing the circle. This value can range
from 0 to 2 * PI, and the default value is 0.
● thetaLength - This property defines to what extent the circle is completed. The default
value is 2 * PI.

const circle = new [Link](


radius, segments,
thetaStart, thetaLength
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Circle</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}

122
[Link]

#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Circle geometry
// a 2d circle in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// Light
const ambientLight = new [Link](0xffffff, 1)

123
[Link]

[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.2)


[Link].x = 2
[Link].y = 3
[Link].z = 4
[Link](pointLight)

// circle
const geometry = new [Link]()
const material = new [Link]({
color: 0xffffff,
wireframe: true,
side: [Link]
})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const circle = new [Link](geometry, material)


[Link](circle)

const circleProps = {
radius: 1,
segments: 8,
thetaStart: 0,
thetaLength: 2 * [Link]
}
const props = [Link]('Properties')
props
.add(circleProps, 'radius', 1, 50)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](circleProps, 'segments', 1, 50).step(1).onChange(redraw)
[Link](circleProps, 'thetaStart', 0, 2 * [Link]).onChange(redraw)

124
[Link]

[Link](circleProps, 'thetaLength', 0, 2 * [Link]).onChange(redraw)


[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

125
[Link]

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

Ring Geometry
The [Link] creates a D disc with a hole in the center. It is very similar to circle
geometry.
● innerRadius - The inner radius of a circle defines the size of the hole in the center. 0
means no hole. The default value is 0.5.
● outerRadius - The outer radius of a circle defines its size. The default value is 1.
● thetaSegments - the number of diagonal segments used to create the circle. The default
value is 8. The more segments, the smoother circle is.
● phiSegments - the number of segments used along the length of the ring. The default
value is 8.

126
[Link]

● thetaStart - The position from which to start drawing the circle. This value can range
from 0 to 2 * PI, and the default value is 0.
● thetaLength - This property defines to what extent the circle is completed. The default
value is 2 * PI.

const ring = new [Link](


innerRadius, outerRadius,
thetaSegments, phiSegments,
thetaStart, thetaLength
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Ring</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;

127
[Link]

height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Ring geometry
// a simple 2d ring in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// Light
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.2)

128
[Link]

[Link].x = 2
[Link].y = 3
[Link].z = 4
[Link](pointLight)

// ring
const geometry = new [Link]()
const material = new [Link]({
color: 0xffffff,
wireframe: true,
side: [Link]
})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const ring = new [Link](geometry, material)


[Link](ring)

const ringProps = {
innerRadius: 1,
outerRadius: 5,
thetaSegments: 8,
phiSegments: 8,
thetaStart: 0,
thetaLength: 2 * [Link]
}
const props = [Link]('Properties')
props
.add(ringProps, 'innerRadius', 1, 50)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](ringProps, 'outerRadius', 1, 50).step(1).onChange(redraw)
[Link](ringProps, 'thetaSegments', 1, 50).step(1).onChange(redraw)
[Link](ringProps, 'phiSegments', 1, 50).step(1).onChange(redraw)

129
[Link]

[Link](ringProps, 'thetaStart', 0, 2 * [Link]).onChange(redraw)


[Link](ringProps, 'thetaLength', 0, 2 * [Link]).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],
[Link],
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

130
[Link]

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

Box Geometry
The [Link] creates a simple 3D box with specified dimensions. This is the expanded
version of PlaneGeometry in z axis as depth.

const box = new [Link](


width, height, depth,
widthSegments, heightSegments, depthSegments
)

131
[Link]

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Cube</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">

132
[Link]

// Cube geometry
// A simple 3d cube in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// Light
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.5)


[Link].x = 2
[Link].y = 3
[Link].z = 4
[Link](pointLight)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// cube
const geometry = new [Link](1, 1, 1)
const material = new [Link]({
color: 0x87ceeb,
wireframe: true
})

133
[Link]

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const cube = new [Link](geometry, material)


[Link](cube)
[Link](cube)
// cube properties
const cubeProps = {
width: 1,
height: 1,
depth: 1,
widthSegments: 1,
heightSegments: 1,
depthSegments: 1,
wireframe: true
}

// GUI for exporimenting cube properties


const props = [Link]('Properties')
props
.add(cubeProps, 'width', 1, 30)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](cubeProps, 'height', 1, 30).step(1).onChange(redraw)
[Link](cubeProps, 'depth', 1, 30).step(1).onChange(redraw)
[Link](cubeProps, 'widthSegments', 1, 30).step(1).onChange(redraw)
[Link](cubeProps, 'heightSegments', 1, 30).step(1).onChange(redraw)
[Link](cubeProps, 'depthSegments', 1, 30).step(1).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],

134
[Link]

[Link],
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])

135
[Link]

[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

Sphere Geometry
The [Link] creates 3D sphere geometries. You can create different types of
sphere-related geometries by passing the arguments.
● radius - The radius of a circle defines its size. The default value is 1.
● widthSegments - number of segments used vertically. This defaults to 8.
● heightSegments - the number of segments used horizontally. This defaults to 6.
● phiStart - The position from which to start drawing the circle. This value can range from
0 to 2 * PI, and the default value is 0.
● phiLength - This property defines to what extent the circle is completed. The default
value is 2 * PI.
● thetaStart - The position from which to start drawing the circle. This value can range
from 0 to 2 * PI, and the default value is 0.
● thetaLength - This property defines to what extent the circle is completed. The default
value is 2 * PI.

const sphere = new [Link](


radius,
widthSegments, heightSegments,
phiStart, phiLength,

136
[Link]

thetaStart, thetaLength
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Sphere</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>

137
[Link]

</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// creating a sphere using Sphere geometry in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// Light
const ambientLight = new [Link](0x87ceeb, 1)
[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.2)


[Link].x = 2
[Link].y = 3
[Link].z = 4
[Link](pointLight)

// sphere
const geometry = new [Link]()
const material = new [Link]({ color: 0xffffff })

138
[Link]

[Link] = 0.7
[Link] = 0.3

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const sphere = new [Link](geometry, material)


[Link](sphere)

const sphereProps = {
radius: 1,
widthSegments: 8,
heightSegments: 6,
phiStart: 0,
phiLength: 2 * [Link],
thetaStart: 0,
thetaLength: 2 * [Link]
}
const props = [Link]('Properties')
props
.add(sphereProps, 'radius', 1, 50)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](sphereProps, 'widthSegments', 1, 50).step(1).onChange(redraw)
[Link](sphereProps, 'heightSegments', 1, 50).step(1).onChange(redraw)
[Link](sphereProps, 'phiStart', 0, 2 * [Link]).onChange(redraw)
[Link](sphereProps, 'phiLength', 0, 2 * [Link]).onChange(redraw)
[Link](sphereProps, 'thetaStart', 0, 2 * [Link]).onChange(redraw)
[Link](sphereProps, 'thetaLength', 0, 2 * [Link]).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],

139
[Link]

[Link],
[Link],
[Link],
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendesphere the scene

140
[Link]

const container = [Link]('#threejs-container')


[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

Cylinder Geometry
To create a cylinder in [Link], you can use the [Link].

● radiusTop - Radius of the cylinder at the top. Default is 1.


● radiusBottom - Radius of the cylinder at the bottom. Default is 1.
● height - Height of the cylinder. Default is 1.
● radialSegments - the number of segments around the circumference of the cylinder.
Default is 8.
● heightSegments - Number of rows of faces along with the height of the cylinder. Default
is 1.
● openEnded - It's a Boolean indicating whether the ends of the cylinder are open or not.
Default is false, meaning closed.
● thetaStart - Start angle for the first segment, defaults to 0.
● thetaLength - The central angle, often called theta, of the circular sector. The default is
2* [Link], which makes for a complete cylinder.

const cylinder = new [Link](


radiusTop, radiusBottom, height,

141
[Link]

radialSegments, heightSegments,
openEnded,
thetaStart, thetaLength
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - cylinder</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>

142
[Link]

<script src="[Link]
gui/0.7.7/[Link]"></script>

</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Cylinder geometry in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// cylinder
const geometry = new [Link]()
const material = new [Link]({
color: 0xffffff,
wireframe: true
})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

143
[Link]

const cylinder = new [Link](geometry, material)


[Link](cylinder)

const cylinderProps = {
radiusTop: 1,
radiusBottom: 1,
height: 1,
radialSegments: 8,
heightSegments: 1,
openEnded: false,
thetaStart: 0,
thetaLength: 2 * [Link]
}
const props = [Link]('Properties')
props
.add(cylinderProps, 'radiusTop', 1, 50)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](cylinderProps, 'radiusBottom', 0, 50).onChange(redraw)
[Link](cylinderProps, 'height', 0, 100).onChange(redraw)
[Link](cylinderProps, 'radialSegments', 1, 50).step(1).onChange(redraw)
[Link](cylinderProps, 'heightSegments', 1, 50).step(1).onChange(redraw)
[Link](cylinderProps, 'openEnded').onChange(redraw)
[Link](cylinderProps, 'thetaStart', 0, 2 * [Link]).onChange(redraw)
[Link](cylinderProps, 'thetaLength', 0, 2 * [Link]).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],
[Link],
[Link],
[Link],
[Link],

144
[Link]

[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendecylinder the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()

145
[Link]

</script>
</body>
</html>

Output

Cone Geometry
You can use [Link] to create a cone. It is very similar to CylinderGeometry,
except it only allows you to set the radius instead of radiusTop and radiusBottom.

const cone = new [Link](


radius, height,
radialSegments, heightSegments,
openEnded,
thetaStart, thetaLength
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />

146
[Link]

<meta name="viewport" content="width=device-width, initial-scale=1.0" />


<title>[Link] - Cone</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Cone geometry in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

147
[Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// cone
const geometry = new [Link]()
const material = new [Link]({
color: 0xffffff,
wireframe: true
})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const cone = new [Link](geometry, material)


[Link](cone)

const coneProps = {
radius: 1,
height: 1,
radialSegments: 8,
heightSegments: 1,
openEnded: false,
thetaStart: 0,
thetaLength: 2 * [Link]
}
const props = [Link]('Properties')
props

148
[Link]

.add(coneProps, 'radius', 1, 50)


.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](coneProps, 'height', 0, 100).onChange(redraw)
[Link](coneProps, 'radialSegments', 1, 50).step(1).onChange(redraw)
[Link](coneProps, 'heightSegments', 1, 50).step(1).onChange(redraw)
[Link](coneProps, 'openEnded').onChange(redraw)
[Link](coneProps, 'thetaStart', 0, 2 * [Link]).onChange(redraw)
[Link](coneProps, 'thetaLength', 0, 2 * [Link]).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],
[Link],
[Link],
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

149
[Link]

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendecone the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

150
[Link]

Torus Geometry
Torus is a tube-like shape that looks like a donut. You can use [Link] to create a
torus in [Link]. The arguments, radialSegments, and tubularSegments are the number of
segments along the radius and tube. With arc property, you can control whether the torus has
drawn a full circle.

const torus = new [Link](


radius, tubeRadius,
radialSegments, tubularSegments,
arc
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Torus</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;

151
[Link]

height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Torus geometry
// creating a torus, a donut like shape in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// torus
const geometry = new [Link]()
const material = new [Link]({
color: 0xffffff,
wireframe: true

152
[Link]

})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const torus = new [Link](geometry, material)


[Link](torus)

const torusProps = {
radius: 1,
tubeRadius: 0.5,
radialSegments: 8,
tubularSegments: 6,
arc: 2 * [Link]
}
const props = [Link]('Properties')
props
.add(torusProps, 'radius', 1, 50)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](torusProps, 'tubeRadius', 0.1, 50).step(0.1).onChange(redraw)
[Link](torusProps, 'radialSegments', 1, 50).step(1).onChange(redraw)
[Link](torusProps, 'tubularSegments', 1, 50).step(1).onChange(redraw)
[Link](torusProps, 'arc', 0, 2 * [Link]).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],
[Link],
[Link]
)
[Link]()

153
[Link]

[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

154
[Link]

Output

TorusKnot Geometry
A torus knot is a special kind of knot that looks like a tube that winds around itself a couple of times.
You can create a torus-knot using [Link]. It's pretty similar to
TorusGeometry with additional properties, the p and q.

● p - It defines how many times the geometry winds around its axis of rotational symmetry.
Default is 2.
● q - It defines how many times the geometry winds around the interior of the torus. This
defaults to 3.

const torusKnot = new [Link](


radius, tubeRadius,
tubularSegments, radialSegments,
p, q
)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Torus Knot</title>
<style>

155
[Link]

* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Torus knot geometry in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()

156
[Link]

[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// torusKnot
const geometry = new [Link]()
const material = new [Link]({
color: 0xffffff,
wireframe: true
})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const torusKnot = new [Link](geometry, material)


[Link](torusKnot)

const torusKnotProps = {
radius: 1,
tubeRadius: 0.5,
radialSegments: 64,
tubularSegments: 8,
p: 2,
q: 3
}
const props = [Link]('Properties')
props
.add(torusKnotProps, 'radius', 1, 50)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))

157
[Link]

[Link](torusKnotProps, 'tubeRadius', 0.1, 50).step(0.1).onChange(redraw)


[Link](torusKnotProps, 'radialSegments', 1, 50).step(1).onChange(redraw)
[Link](torusKnotProps, 'tubularSegments', 1, 50).step(1).onChange(redraw)
[Link](torusKnotProps, 'p', 1, 20).step(1).onChange(redraw)
[Link](torusKnotProps, 'q', 1, 20).step(1).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
[Link],
[Link],
[Link],
[Link],
torusKnotProps.p,
torusKnotProps.q
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation

158
[Link]

function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

Polyhedron Geometry
A polyhedron is a geometry that has only flat faces and straight edges. You can draw different
types of polyhedrons by specifying vertices and indices.

159
[Link]

● vertices - Array of points that make up the polyhedron.


● indices - Array of indices that make up the faces from the vertices.
● radius - The radius of the final shape. This defaults to 1.
● detail - How many levels to subdivide the geometry. The more detail, the smoother the
shape.
The following code creates a polyhedron with four faces.

const vertices = [
1, 1, 1,
-1, -1, 1,
-1, 1, -1,
1, -1, -1
]

const indices = [
2, 1, 0,
0, 3, 2,
1, 3, 0,
2, 3, 1
]
const geometry = new [Link](vertices, indices, radius,
detail)

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Polyhedron</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,

160
[Link]

Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;


}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Creating a tetrahedron using Polyhedron geometry in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

const axesHepler = new [Link](10)


[Link](axesHepler)

161
[Link]

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// prettier-ignore
const vertices = [
1, 1, 1,
-1, -1, 1,
-1, 1, -1,
1, -1, -1
]

// prettier-ignore
const indices = [
2, 1, 0,
0, 3, 2,
1, 3, 0,
2, 3, 1
]

const geometry = new [Link](vertices, indices)


const material = new [Link]({
color: 0xffffff
})

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const plane = new [Link](geometry, material)


[Link](plane)

// experimenting plane properties


const planeProps = {

162
[Link]

radius: 1,
detail: 1
}
const props = [Link]('Properties')
props
.add(planeProps, 'radius', 1, 30)
.step(1)
.onChange(redraw)
.onFinishChange(() => [Link]([Link]))
[Link](planeProps, 'detail', 1, 30).step(1).onChange(redraw)
[Link]()

function redraw() {
let newGeometry = new [Link](
verticesOfCube,
indicesOfFaces,
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)

163
[Link]

[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

[Link] also has geometries for some common polyderons.

164
[Link]

Polyhedron No. of faces Code

Tetrahedron 4 [Link]

Octahedron 8 [Link]

Dodecahedron 12 [Link]

Icosahedron 20 [Link]

Check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Polyhedrons</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}

165
[Link]

</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Various built-in polyhedron geometries in [Link]
// Tetrahedron, Octahedron, Dodecahedron, Icosahedron

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// tetrahedron
const geometry = new [Link]()
const material = new [Link]()

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

166
[Link]

const tetrahedron = new [Link](geometry, material)


[Link](-5, 0, 0)
[Link](tetrahedron)

const tetrahedronProps = {
radius: 1,
detail: 1
}
const tetraProps = [Link]('Tetrahedron')
tetraProps
.add(tetrahedronProps, 'radius', 1, 50)
.step(1)
.onChange(redrawTetrahedron)
.onFinishChange(() => [Link]([Link]))
[Link](tetrahedronProps, 'detail', 1, 50, 1).onChange(redrawTe
trahedron)
[Link]()

function redrawTetrahedron() {
let newGeometry = new [Link](
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// octahedron
const geometry1 = new [Link]()
const octahedron = new [Link](geometry1, material)
[Link](-2.5, 0, 0)
[Link](octahedron)

const octahedronProps = {
radius: 1,
detail: 1

167
[Link]

}
const octaProps = [Link]('Octahedron')
octaProps
.add(octahedronProps, 'radius', 1, 50)
.step(1)
.onChange(redrawOctahedron)
.onFinishChange(() => [Link]([Link]))
[Link](octahedronProps, 'detail', 1, 50, 1).onChange(redrawOcta
hedron)
[Link]()

function redrawOctahedron() {
let newGeometry = new [Link](
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// dodecahedron
const geometry2 = new [Link]()

const dodecahedron = new [Link](geometry2, material)


[Link](0, 0, 0)
[Link](dodecahedron)

const dodecahedronProps = {
radius: 1,
detail: 1
}
const dodecaProps = [Link]('Dodecahedron')
dodecaProps
.add(dodecahedronProps, 'radius', 1, 50)
.step(1)
.onChange(redrawDodecahedron)
.onFinishChange(() => [Link]([Link]))

168
[Link]

[Link](dodecahedronProps, 'detail', 1, 50, 1).onChange(redraw


Dodecahedron)
[Link]()

function redrawDodecahedron() {
let newGeometry = new [Link](
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}

// icosahedron
const geometry3 = new [Link]()

const icosahedron = new [Link](geometry3, material)


[Link](2.5, 0, 0)
[Link](icosahedron)

const icosahedronProps = {
radius: 1,
detail: 1
}
const icosaProps = [Link]('Icosahedron')
icosaProps
.add(icosahedronProps, 'radius', 1, 50)
.step(1)
.onChange(redrawIcosahedron)
.onFinishChange(() => [Link]([Link]))
[Link](icosahedronProps, 'detail', 1, 50, 1).onChange(redrawIc
osahedron)
[Link]()

function redrawIcosahedron() {
let newGeometry = new [Link](
[Link],

169
[Link]

[Link]
)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

const polyhedrons = [tetrahedron, octahedron, dodecahedron, icosahedron]


[Link]((hedron) => {
[Link].x += 0.005
[Link].y += 0.01
})

[Link](scene, camera)
}

// rendetetrahedron the scene


const container = [Link]('#threejs-container')

170
[Link]

[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

Learn more about geometries here.

171
[Link] – Materials [Link]

Material is like the skin of the object. It defines the outer appearance of the geometry. [Link]
provides many materials to work. We should choose the type of material according to our needs.
In this chapter, we'll discuss the most commonly used materials in [Link].

MeshBasicMaterial
It is the very basic material in [Link]. It is used to create and display objects of solid color or
wireframe. It is self-illuminating and is not affected by lighting.

const geometry = new [Link](2, 2, 2)


const material = new [Link]({
color: 0x87ceeb,
wireframe: true,
wireframeLinewidth: 2,
})

const cube = new [Link](geometry, material)

Sometimes it’s hard to distinguish between two adjacent surfaces of the same color. If you create
a sphere, it appears like a 2D circle. Although it seems 2D, it should be 3D.

MeshDepthMaterial
It uses the distance from the camera to determine how to color your mesh in a greyscale. White is
nearest, and black is farthest.

const geometry = new [Link]()


const material = new [Link]()
const torusKnot = new [Link](geometry, material)

You can understand better in this example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />

172
[Link]

<title>[Link] - MeshDepthMaterial </title>


<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Using mesh depth material
// white means, top point. black means, bottom point

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

173
[Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// Light
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.5)


[Link].x = 2
[Link].y = 3
[Link].z = 4
[Link](pointLight)

// camera
const camera = new [Link](30, width / height, 250, 550)
[Link].z = 450

// torusKnot
const geometry = new [Link](50, 20, 128, 64, 2, 3)
const material = new [Link]()

const materialFolder = [Link]('Material')


[Link](material, 'wireframe')
[Link]()

const torusKnot = new [Link](geometry, material)


[Link](torusKnot)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

174
[Link]

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer({ logarithmicDepthBuffer: true })
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

175
[Link]

Output

MeshNormalMaterial
This material uses the magnitude of the x/y/z values of the faces’ normal vectors to calculate and
set the red/green/blue values of the colors displayed on the face.
How does it work? - x is red, y is green, and z is blue, so things facing to the right are pink,
to the left are aqua, up are light green, down are be purple, and toward the screen are be
lavender.

const geometry = new [Link](2, 2, 2)


const material = new [Link]()

const cube = new [Link](geometry, material)

In the following example, you can see that every face has its color based on the normal of the face.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Cube</title>
<style>

176
[Link]

* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Using mesh normal material
// each face has different color

import { OrbitControls } from "[Link]


ls/[Link]"

// GUI
const gui = new [Link]()

// sizes
let width = [Link]

177
[Link]

let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](30, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]()
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[Link]()

const cube = new [Link](geometry, material)


[Link](cube)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)

178
[Link]

[Link]([Link]([Link], 2))
const controls = new OrbitControls(camera, [Link])

// animation
function animate() {
requestAnimationFrame(animate)

[Link].x += 0.005
[Link].y += 0.01

[Link]()
[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

179
[Link]

MeshLambertMaterial
You can use this material to create dull-looking, non-shiny surfaces. It is a very easy-to-use
material that responds to the lighting sources in the scene. It has two main properties:
● color - This is the color of the material.
● emissive - This is the color that the material emits. You can use this to create objects
that look like they glow.

const geometry = new [Link](2, 2, 2)


const material = new [Link]({ color, emissive })

const cube = new [Link](geometry, material)

MeshPhongMaterial
This material is similar to MeshLambertMaterial but can create more shiny surfaces. If you use
this material without lighting, the camera shows nothing, and it is in black. You can use a white
AmbientLight to make it visible.

const geometry = new [Link](2, 2, 2)


const material = new [Link]({ color, emissive, shininess })

const cube = new [Link](geometry, material)

MeshStandardMaterial
It is similar but gives a more accurate and realistic looking result than the MeshLambertMaterial
or MeshPhongMaterial. Instead of shininess, it has two properties: roughness and metalness.

const geometry = new [Link](2, 2, 2)


const material = new [Link]({ color, roughness, metalness })

const cube = new [Link](geometry, material)

MeshPhysicalMaterial
It is pretty similar to MeshStandardMaterial. You can control the reflectivity of the material. The
default reflectivity is 0.5, and you can vary it between 0 and 1.

const geometry = new [Link](2, 2, 2)


const material = new [Link]({
color,
roughness,
metalness,

180
[Link]

reflectivity,
})

const cube = new [Link](geometry, material)

In this example, you can experiment and understand the differences between
MeshLambertMaterial, MeshPhongMaterial, MeshStandardMaterial, and
MeshPhysicalMaterial.

Now, check out the following example.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Materials</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>

181
[Link]

<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Comparision between MeshLambert, MeshPhong, MeshStandard and MeshPh
ysical materials

import { OrbitControls } from "[Link]


ls/[Link]"

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)

const light = new [Link]()


[Link](0, 10, 10)
[Link](light)
// for shadow
[Link] = true
[Link] = 1024
[Link] = 1024
[Link] = 0.5
[Link] = 100

182
[Link]

[Link](light)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// geometies
const materials = [
new [Link]({ color: 0x87ceeb }),
new [Link]({ color: 0x87ceeb }),
new [Link]({ color: 0x87ceeb }),
new [Link]({ color: 0x87ceeb })
]

const geometry = new [Link](0.7, 0.28, 128, 64, 2, 3)


const meshes = [
new [Link](geometry, materials[0]),
new [Link](geometry, materials[1]),
new [Link](geometry, materials[2]),
new [Link](geometry, materials[3])
]
[Link]((mesh, i) => {
[Link](-6 + 3 * i, 0, 0)
[Link](mesh)
})

const objColor = {
color: materials[0].[Link](),
emissive: materials[0].[Link](),
specular: materials[1].[Link]()
}
[Link](objColor, 'color').onChange(() => {
[Link]((material) => {
[Link]([Link])

183
[Link]

})
})
[Link](objColor, 'emissive').onChange(() => {
[Link]((material) => {
[Link]([Link])
})
})

// gui folders
const folders = [
'MeshLambertMaterial',
'MeshPhongMaterial',
'MeshStandardMaterial',
'MeshPhysicalMaterial'
]
[Link]((fol, i) => {
let folder = [Link](fol)
let temp = folders[i]
folders[i] = folder
//[Link]()
})

for (let i = 0; i < [Link]; i++) {


if (i != 0) {
folders[i].add(materials[i], 'flatShading')
}
if (i < 2) {
folders[i].add(materials[i], 'reflectivity', 0, 1)
folders[i].add(materials[i], 'refractionRatio', 0, 1)
}
if (i > 2) {
folders[i].add(materials[i], 'roughness', 0, 1)
folders[i].add(materials[i], 'metalness', 0, 1)
}
folders[i].add(materials[i], 'wireframe')
folders[i].add(materials[i], 'vertexColors')
}

184
[Link]

folders[1].addColor(objColor, 'specular').onChange(() => {


materials[1].[Link]([Link])
})
folders[1].add(materials[1], 'shininess', 1, 100)

folders[3].add(materials[3], 'reflectivity', 0, 1)
folders[3].add(materials[3], 'clearcoat', 0, 1)
folders[3].add(materials[3], 'clearcoatRoughness', 0, 1)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))
const controls = new OrbitControls(camera, [Link])

// animation
function animate() {
requestAnimationFrame(animate)

[Link]((mesh) => {
[Link].x += 0.005
[Link].y += 0.01
})

[Link]()

185
[Link]

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

There are many other materials in [Link]. You can learn more here.

Using Multiple Materials


Until now, while creating a Mesh, you added a single material to it. There are also cases where you
want to combine multiple materials. You can do that by passing an array of materials. But you
should not use Mesh. Instead, you can use createMultipleMaterialObject of SceneUtils. For
example, the following code combines [Link] with a material that shows
you the wireframe of the geometry.

const geometry = new [Link](1, 1, 1)

const material1 = new [Link]({

186
[Link]

color: 0xff0000,
transparent: true,
opacity: 0.7,
})
const material2 = new [Link]({ wireframe: true })

const cube = [Link](cylinderGeometry, [


material1,
material2,
])

187
[Link] – Textures [Link]

The texture is an image or color added to the material to give more detail or beauty. The texture is
an essential topic in [Link]. In this section, we'll see how to apply a basic texture to our material.

Basic Texture
First, you should create a loader. [Link] has a built-in function TextureLoader() to load
textures into your [Link] project. Then you can load any texture or image by specifying its path
in the load() function.

const loader = new [Link]()


[Link]('/path/to/the/image')

Then, set the map property of the material to this texture. That's it; you applied a texture to the
plane geometry.
Textures have settings for repeating, offsetting, and rotating a texture. By default, textures in
[Link] do not repeat. There are two properties, wrapS for horizontal wrapping and wrapT for
vertical wrapping to set whether a texture repeats. And set the repeating mode to
[Link].

[Link] = [Link]
[Link] = [Link]
[Link] = [Link]

In [Link], you can choose what happens both when the texture is drawn larger than its original
size and what happens when it's drawn smaller than its original size.
For setting the filter, when the texture is larger than its original size, you set [Link]
property to either [Link] or [Link].

● NearestFilter - This filter uses the color of the nearest texel that it can find.
● LinearFilter - This filter is more advanced and uses the color values of the four
neighboring texels to determine the correct color.
And, you can add how many times to repeat the texture.

const timesToRepeatHorizontally = 4
const timesToRepeatVertically = 2
[Link](timesToRepeatHorizontally, timesToRepeatVertically)

Check out the following example.

188
[Link]

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Checker Board</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Creating a checker-board using Textures

189
[Link]

// applying the texture to 2d plane geometry

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](75, width / height, 0.1, 100)
[Link](0, 0, 10)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(60).step(10)
[Link]()

// Light
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)

// texture
const planeSize = 10

const loader = new [Link]()


const texture = [Link](' [Link]
[Link]/[Link] ')
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]

const repeats = planeSize / 2


[Link](repeats, repeats)

190
[Link]

class StringToNumberHelper {
constructor(obj, prop) {
[Link] = obj
[Link] = prop
}
get value() {
return [Link][[Link]]
}
set value(v) {
[Link][[Link]] = parseFloat(v)
}
}

const wrapModes = {
ClampToEdgeWrapping: [Link],
RepeatWrapping: [Link],
MirroredRepeatWrapping: [Link]
}

function updateTexture() {
[Link] = true
}

gui
.add(new StringToNumberHelper(texture, 'wrapS'), 'value', wrapModes)
.name('[Link]')
.onChange(updateTexture)
gui
.add(new StringToNumberHelper(texture, 'wrapT'), 'value', wrapModes)
.name('[Link]')
.onChange(updateTexture)
[Link]([Link], 'x', 0, 5, 0.01).name('[Link].x')
[Link]([Link], 'y', 0, 5, 0.01).name('[Link].y')

// plane for board


const geometry = new [Link](planeSize, planeSize)
const material = new [Link]({

191
[Link]

map: texture,
side: [Link]
})
const board = new [Link](geometry, material)
[Link](0, 0, 0)
[Link](board)

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
[Link]([Link])
animate()
</script>

192
[Link]

</body>
</html>

Output

Texture Mapping

base color map


It is the basic colored image you add to the object to the texture. With a base color map we add
colors to the surface.

const textureMap = new [Link]().load('/path/to/texture-map')


[Link] = textureMap

You can add the effect of depth using a bump map or normal map or distance map.

bump map
A bump map is a grayscale image, where the intensity of each pixel determines the height. You
can just set the material bumpMap property to the texture. It adds fine details to the texture.

const textureBumpMap = new [Link]().load('/path/to/bump-map')


[Link] = textureBumpMap

normal maps
A normal map describes the normal vector for each pixel, which should be used to calculate how
light affects the material used in the geometry. It creates an illusion of depthness to the flat surface.

const textureNormalMap = new [Link]().load('/path/to/normal-map')

193
[Link]

[Link] = textureNormalMap

displacement map
While the normal map gives an illusion of depth, we change the model's shape, with a displacement
map based on the information from the texture.

const textureDisplacementMap = new [Link]().load(


'/path/to/displacement-map'
)
[Link] = textureDisplacementMap

roughness map
The roughness map defines which areas are rough and that affects the reflection sharpness from
the surface.

const textureRoughnessMap = new [Link]().load(


'/path/to/roughness-map'
)
[Link] = textureRoughnessMap

ambient occlusion map


It highlights the shadow areas of the object. It requires a second set of UVs.

const textureAmbientOcclusionMap = new [Link]().load(


'/path/to/AmbientOcclusion-map'
)
[Link] = textureAmbientOcclusionMap
// second UV
[Link].uv2 = [Link]

If you compare the objects with roughness map and ambient occlusion map, you can observe that
The shadows are more highlighted after using aoMap.

metalness map
It defines how much the material is like a metal.

const textureMetalnessMap = new [Link]().load(


'/path/to/metalness-map'
)
[Link] = textureMetalnessMap

Now, check out the following example.

194
[Link]

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Texture Mapping</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Using different types of texture maps

195
[Link]

import { OrbitControls } from "[Link]


ls/[Link]"

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0xffffff)

// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)

const light = new [Link](0xffffff, 4.0)


[Link](0, 10, 20)
[Link] = true
[Link] = 512
[Link] = 512
[Link] = 0.5
[Link] = 100
[Link](light)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 10)

// textures
const loader = new [Link]()
const texture = [Link]('[Link]
[Link]/[Link]')
const normalmap = [Link]('[Link]
[Link]/[Link]')
const heightmap = [Link]('[Link]
[Link]/[Link]')

196
[Link]

const roughmap = [Link]('[Link]


[Link]/[Link]')

const ambientOcclusionmap = [Link]('[Link]


[Link]/[Link]')
const metallicmap = [Link]('[Link]
[Link]/[Link]')

// plane
const planeGeometry = new [Link](100, 100)
const plane = new [Link](
planeGeometry,
new [Link]({ color: 0xffffff, side: [Link] })
)
[Link](-[Link] / 2)
[Link].y = -2.75
[Link] = true
[Link](plane)

// object
const geometry = new [Link](1, 64, 64)
const material1 = new [Link]({
map: texture,
side: [Link]
})
const object1 = new [Link](geometry, material1)
[Link](-2.5, 1.5, 0)
[Link] = true
[Link](object1)

// normal map
const material2 = new [Link]({
color: 0xffffff,
map: texture,
side: [Link],
normalMap: normalmap
})
const object2 = new [Link](geometry, material2)
[Link](0, 1.5, 0)

197
[Link]

[Link] = true
[Link](object2)

// displacement map
const material3 = new [Link]({
color: 0xffffff,
map: texture,
side: [Link],
normalMap: normalmap,
displacementMap: heightmap,
displacementScale: 0.05
})
const object3 = new [Link](geometry, material3)
[Link](2.5, 1.5, 0)
[Link] = true
[Link](object3)
[Link](object3)

// roughness map
const material4 = new [Link]({
color: 0xffffff,
map: texture,
side: [Link],
normalMap: normalmap,
displacementMap: heightmap,
displacementScale: 0.05,
roughnessMap: roughmap,
roughness: 0.5
})
const object4 = new [Link](geometry, material4)
[Link](-2.5, -1.5, 0)
[Link] = true
[Link](object4)
[Link](object4)

// ambient occlusion map


const material5 = new [Link]({

198
[Link]

color: 0xffffff,
map: texture,
side: [Link],
normalMap: normalmap,
displacementMap: heightmap,
displacementScale: 0.05,
roughnessMap: roughmap,
roughness: 0.1,
aoMap: ambientOcclusionmap
})
const object5 = new [Link](geometry, material5)
[Link](0, -1.5, 0)
[Link].uv2 = [Link]
[Link] = true
[Link](object5)
[Link](object5)

// for env maps


const cubeRenderTarget = new [Link](128, {
format: [Link],
generateMipMaps: true,
minFilter: [Link],
encoding: [Link]
})

const cubeCamera = new [Link](1, 10000, cubeRenderTarget)


[Link](0, 100, 0)
[Link](cubeCamera)

// metallic map
const material6 = new [Link]({
color: 0xffffff,
map: texture,
side: [Link],
normalMap: normalmap,
displacementMap: heightmap,
displacementScale: 0.15,

199
[Link]

roughnessMap: roughmap,
roughness: 0.1,
aoMap: ambientOcclusionmap,
metalnessMap: metallicmap,
metalness: 1,
envMap: [Link]
})
const object6 = new [Link](geometry, material6)
[Link](2.5, -1.5, 0)
[Link].uv2 = [Link]
[Link] = true
[Link](object6)
[Link](object6)

[Link]([Link])

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer - anti-aliasing
const renderer = new [Link]({ antialias: true })
[Link] = true
[Link](width, height)
[Link]([Link]([Link], 2))

const controls = new OrbitControls(camera, [Link])

// animation
function animate() {

200
[Link]

requestAnimationFrame(animate)

let objects = [object1, object2, object3, object4, object5, object6]

[Link]((i) => {
//[Link].x += 0.005
[Link].y += 0.01
})
[Link]()
[Link](renderer, scene)

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

201
[Link]

There are some other maps for creating a real-world model in computer graphics. You can learn
more here.

202
[Link] – Drawing Lines [Link]

You have learned about quite a lot of materials in [Link]. Now let's see some unique materials
used in drawing lines. We can draw various shapes and patterns using lines.

Using BufferGeometry
[Link] is the base class of all the built-in geometries in [Link]. You can create
your geometry by passing an array of vertices of the geometry.
Learn more about BufferGeometry here.

const points = []
[Link](new THREE.Vector3(-10, 0, 0))
[Link](new THREE.Vector3(0, -10, 0))
[Link](new THREE.Vector3(10, 0, 0))

These are some additional elements [Link] provides us to create our geometries.
THREE.Vector3(x, y, z) - It makes a point in 3D space. In the above code, we are adding 3
points to the points array.

const geometry = new [Link]().setFromPoints(points)

[Link](), as mentioned before it creates our geometry. We use the


setFromPoints method to set the geometry using the array of points.

Note: Lines are drawn between each consecutive pair of vertices, but not between the first and
last (the line is not closed.)

const material = new [Link]({


// for normal lines
color: 0xffffff,
linewidth: 1,
linecap: 'round', //ignored by WebGLRenderer
linejoin: 'round', //ignored by WebGLRenderer
})

// or
const material = new [Link]({
// for dashed lines
color: 0xffffff,
linewidth: 1,

203
[Link]

scale: 1,
dashSize: 3,
gapSize: 1,
})

These are the unique materials for lines. You can use any one of [Link] or
[Link].

const line = new [Link](geometry, material)

Now, instead of using [Link], we use [Link] for drawing lines. Now, you see a "V"
shape drawn using lines on the screen.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Line basic</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}

204
[Link]

</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Creating a line using LineBasicMaterial

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 50)
[Link](0, 0, 0)
const camFolder = [Link]('Camera')
[Link]([Link], 'z', 10, 100)
[Link]()

// Line
const points = []
[Link](new THREE.Vector3(-10, 0, 0))
[Link](new THREE.Vector3(0, -20, 0))
[Link](new THREE.Vector3(10, 0, 0))

const folders = [[Link]('Poin 1'), [Link]('Poin 2'), gui


.addFolder('Poin 3')]

205
[Link]

[Link]((folder, i) => {
[Link](points[i], 'x', -30, 30, 1).onChange(redraw)
[Link](points[i], 'y', -30, 30, 1).onChange(redraw)
[Link](points[i], 'z', -30, 30, 1).onChange(redraw)
[Link]()
})

const geometry = new [Link]().setFromPoints(points)


const material = new [Link]({
color: 0xffffff,
linewidth: 2
})
const line = new [Link](geometry, material)
[Link](0, 10, 0)
[Link](line)

function redraw() {
let newGeometry = new [Link]().setFromPoints(points)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

206
[Link]

// animation
function animate() {
requestAnimationFrame(animate)

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

You can create any type of geometry wireframe using lines by specifying the vertices. Check out
the following example where we are drawing dashed lines.

[Link]
<!DOCTYPE html>
207
[Link]

<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - Dashed line</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Creating dashed line using LineDashedMaterial

// GUI
const gui = new [Link]()

208
[Link]

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// camera
const camera = new [Link](45, width / height, 0.1, 100)
[Link](0, 0, 50)
[Link](0, 0, 0)
const camFolder = [Link]('Camera')
[Link]([Link], 'z', 10, 100)
[Link]()

// Line
const points = []
[Link](new THREE.Vector3(-10, 0, 0))
[Link](new THREE.Vector3(0, -20, 0))
[Link](new THREE.Vector3(10, 0, 0))

const folders = [[Link]('Poin 1'), [Link]('Poin 2'), gui


.addFolder('Poin 3')]
[Link]((folder, i) => {
[Link](points[i], 'x', -30, 30, 1).onChange(redraw)
[Link](points[i], 'y', -30, 30, 1).onChange(redraw)
[Link](points[i], 'z', -30, 30, 1).onChange(redraw)
[Link]()
})

const geometry = new [Link]().setFromPoints(points)


const material = new [Link]({
color: 0xffffff,
linewidth: 2,
scale: 1,

209
[Link]

dashSize: 3,
gapSize: 2
})

const line = new [Link](geometry, material)


[Link]()
[Link](0, 10, 0)
[Link](line)

[Link](line)
function redraw() {
let newGeometry = new [Link]().setFromPoints(points)
[Link]()
[Link] = newGeometry
}

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer()
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link](scene, camera)

210
[Link]

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

Output

211
[Link] – Animations [Link]

Animations give life to our websites, as you can see that most of the examples use animations.
Let's see how to add basic animations to our [Link] web application.
If you want to add animations to your [Link] scene, you'll need to render the scene multiple
times. To do that, you should use the standard HTML5 requestAnimationFrame functionality.

function animate() {
// schedule multiple rendering
requestAnimationFrame(animate)

[Link](scene, camera)
}

The above code executes the argument passes to requestAnimationFrame, animate function,
at regular intervals, and also renders the scene multiple times (every 60ms).
You now have your animation loop, so any changes made to your model, camera, or other objects
in the scene can now be done from within the animate function.

Let's create a simple rotating animation.

function animate() {
requestAnimationFrame(animate)
// rotating the cube
[Link].x += 0.005
[Link].y += 0.01
[Link](scene, camera)
}

The above code creates a rotating cube. Every time the animate renders, the cube rotates by the
specified values, which repeats as an infinite loop.
You can also add animation to any other element in the scene. Check out this example and play
around the scene exploring different animations.
You can also use different animation libraries like [Link], Greensock, to create professional
animations using [Link].
In the following section, let's use [Link] to add animations to our 3D objects.

212
[Link]

Using [Link] in the [Link] project


First things first, you should include the library in your project. Add a script tag or install from npm.

<script src="path/to/[Link]"></script>

To use this library, we need to first create an instance of a [Link] object.

const initial = { x: 0, y: 1.25, z: 0, rot: 0 }


const final = { x: 5, y: 15, z: -10, rot: 2 * [Link] }
const tween = new [Link](initial)

It creates a [Link] instance. We can use this instance to move the provided properties from
the initial value to the final value.

[Link](final)

With to function, we tell the tween object that we want to change the initial values to final values
slowly. So, we vary the x property from 0 to 5. The second parameter, which is 5000, defines how
many milliseconds this change should take.
You can also choose how the value changes over time. For instance, you can use a linear easing
function. It changes the values at a constant rate, which starts with small changes and quickly
increases. Many more easing functions are predefined in TWEEN.

[Link]([Link])

To make the 3D object animate, we need to be notified at every change. This is done with
onUpdate(). If you want to be notified at the end of the tween, use onComplete().

[Link](function () {
[Link](this.x, this.y, this.z)
[Link]([Link], [Link], [Link])
})

There are several other settings you can use on the tween object to control how the animation
behaves. In this case, we tell the tween object to repeat its animation indefinitely and use a
yo-yo effect that reverses the animation.

[Link](Infinity)
[Link](true)

Finally, we can start the tween object by calling the start function.

[Link]()

At this point, nothing happens. You have to update the tween so that it is updated whenever the
text the scene renders. You can call it in the animate function.

function animate() {
requestAminationFrame(animate)

213
[Link]

[Link]()
}

Now, you can see the effect. Similarly, you can use any animation library with [Link].

214
[Link] – Creating Text [Link]

Often you need to add text to your scene. In this chapter, let's see how to add 2D and 3D text to
our scene.

Draw Text to Canvas and Use as a Texture


This is the easiest way to add 2D text to your scene. you can create canvas using JavaScript andd
add it to the dom.

const canvas = [Link]('canvas')


const context = [Link]('2d')

The code above creates a canvas element, and we set the context to 2d. The
[Link]() method returns an object that provides methods and properties for
drawing on the canvas, which it can use to draw text, lines, boxes, circles, and more.

[Link] = 'green'
[Link] = '60px sans-serif
[Link]('Hello World!', 0, 60)

The fillText() is a method of a 2D drawing context. The fillText() method allows you to
draw a text string at a coordinate with the fill (color) derived from the fillStyle you provided. You
can set the font of the text using the font property.

The above code set the font to 60-pixel-tall san-serif and the fill style to green. The text
'Hello, World!' is drawn starting at the coordinates (0, 60).

// canvas contents are used for a texture


const texture = new [Link](canvas)
[Link] = true

To create a texture from a canvas element, we need to create a new instance of [Link]
and pass in the canvas element we made. The code above creates a texture using the canvas (in
this case, our text). The needsUpdate parameter of the texture is set to true. It informs [Link]
that our canvas texture has changed and needs to be updated the next time the scene is rendered.
Now, create a plane geometry and add this as a texture to the material.

var material = new [Link]({


map: texture,
side: [Link],
})
[Link] = true
var mesh = new [Link](new [Link](50, 10), material)

215
[Link]

Using Text Geometry


[Link] is another type of geometry that generates text as a single geometry. It
takes two arguments, text - the text you want to render, and other parameters.

Parameters
● font - This is the name of the font.
● size - Size of the text. Default is 100.
● height - The height property defines the depth of the text; in other words, how far the
text extrudes to make it 3D. This defaults to 50.
● curveSegments - Number of points on the curves. Default is 12.
● bevelEnabled - A bevel provides a smooth transition from the front of the text to the
side. If you set this value to true, it adds a bevel to the rendered text. By default, it is
false.
● bevelThickness - If you've set bevelEnabled to true, it defines how deep the bevel is.
Default is 10.
● bevelSize - It determines how high the bevel is. Default is equal to 8.
● bevelOffset - How far from text outline bevel starts. Default is 0.
● bevelSegments - The number of bevel segments. Default is 3.

You need to use [Link] to load fonts from their [Link] files.

const loader = new [Link]()

[Link]('fonts/helvetiker_regular.[Link]', function (font) {


const geometry = new [Link]('Hello [Link]!', {
font: font,
size: 3,
height: 0.2,
curveSegments: 12,
bevelEnabled: false,
bevelThickness: 0.5,
bevelSize: 0.3,
bevelOffset: 0,
bevelSegments: 5,
})
})

Now, you should add some material to it and create a mesh.

const material = new [Link]([


new [Link]({
color: 0xff22cc,

216
[Link]

flatShading: true,
}), // front
new [Link]({
color: 0xffcc22
}), // side
])
const mesh = new [Link](geometry, material)
[Link] = 'text'
[Link](mesh)

Note: There is one thing you need to take into account when working with [Link]
and materials. It can take two materials as an array: one for the front of rendered text and another
for the side of the text. If you just pass in one material, it gets applied to both the front and the
side.
Now, you can see the text rendered to the scene. Check out the following example.

[Link]
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - 2d text</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}

217
[Link]

#threejs-container {
position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Adding 2d text to [Link] scene
// Writing on canvas and then adding the canvas as a texture to material

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]
const size = 256

const container = [Link]('#threejs-container')


const canvas = [Link]('canvas'),
ctx = [Link]('2d')

function changeCanvas() {
[Link] = '20pt Arial'
[Link] = 'white'
[Link](0, 0, [Link], [Link])
[Link] = 'black'
[Link] = 'center'
[Link] = 'middle'
[Link]('Hello world!', [Link] / 2, [Link] / 2)

218
[Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// lights
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.5)


[Link].x = 20
[Link].y = 30
[Link].z = 40
[Link](pointLight)

// camera
const camera = new [Link](70, width / height, 1, 1000)
[Link].z = 500
[Link](camera)

// renderer
const renderer = new THREE.WebGL1Renderer({ antialias: true })
[Link](width, height)
[Link]([Link]([Link], 2))

[Link]([Link])
[Link](scene, camera)

// cube
const texture = new [Link](canvas)
const material = new [Link]({ map: texture })
const geometry = new [Link](200, 200, 200)
const mesh = new [Link](geometry, material)
[Link](mesh)

[Link] = [Link] = size

219
[Link]

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

[Link]([Link], [Link])
[Link](scene, camera)
})

// animation
function animate() {
requestAnimationFrame(animate)

changeCanvas()
[Link] = true
[Link].y += 0.01
[Link](scene, camera)
}
animate()
</script>
</body>
</html>

220
[Link]

Output

Let us now take another example to see how to add 3D text in a scene.

[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>[Link] - 3d text</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-
system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu,
Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
html,
body {
height: 100vh;
width: 100vw;
}
#threejs-container {

221
[Link]

position: block;
width: 100%;
height: 100%;
}
</style>
<script src="[Link]
[Link]"></script>
<script src="[Link]
gui/0.7.7/[Link]"></script>
</head>
<body>
<div id="threejs-container"></div>
<script type="module">
// Creating 3d text using Text Geometry in [Link]

// GUI
const gui = new [Link]()

// sizes
let width = [Link]
let height = [Link]

// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)

// lights
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)

const pointLight = new [Link](0xffffff, 0.5)


[Link].x = 20
[Link].y = 30
[Link].z = 40
[Link](pointLight)

// camera

222
[Link]

const camera = new [Link](30, width / height, 0.1, 1000)


[Link](0, 0, 50)
const camFolder = [Link]('Camera')
[Link]([Link], 'z').min(10).max(500).step(10)
[Link]()

function createMaterial() {}

const loader = new [Link]()


// promisify font loading
function loadFont(url) {
return new Promise((resolve, reject) => {
[Link](url, resolve, undefined, reject)
})
}

async function doit() {


const font = await loadFont(
'[Link]
)

let text = 'Hello World !'


const geometry = new [Link](text, {
font: font,
size: 3,
height: 0.2,
curveSegments: 12,
bevelEnabled: true,
bevelOffset: 0,
bevelThickness: 0.5,
bevelSize: 0.3,
bevelSegments: 5
})
const material = [
new [Link]({
color: 0xff22cc,
flatShading: true

223
[Link]

}), // front
new [Link]({
color: 0xffcc22
}) // side
]
const mesh = new [Link](geometry, material)
[Link]()
[Link]()
[Link]([Link]).multiplyScalar(-1)
[Link].x = -[Link].x / 2

const parent = new THREE.Object3D()


[Link](mesh)

[Link](parent)

const opts = [Link]


[Link](opts)
const geoProps = {
font: [Link],
size: [Link],
height: [Link],
curveSegments: [Link],
bevelEnabled: [Link],
bevelOffset: [Link],
bevelThickness: [Link],
bevelSize: [Link],
bevelSegments: [Link]
}
[Link](geoProps)

// GUI for exporimenting cube properties


const props = [Link]('Properties')
props
.add(geoProps, 'size', 1, 30)
.step(1)
.onChange(redraw)

224
[Link]

.onFinishChange(() => [Link]([Link]))


[Link](geoProps, 'height', 0, 30).step(0.1).onChange(redraw)
[Link](geoProps, 'curveSegments', 1, 30).step(1).onChange(redraw)
[Link](geoProps, 'bevelEnabled').onChange(redraw)
[Link](geoProps, 'bevelOffset', 0, 1).onChange(redraw)
[Link](geoProps, 'bevelThickness', 0, 3).onChange(redraw)
[Link](geoProps, 'bevelSize', 0, 3).onChange(redraw)
[Link](geoProps, 'bevelSegments', 1, 8).step(1).onChange(redraw)
[Link]()

function redraw() {
[Link](0, 0, 80)
let newGeometry = new [Link](text, {
font: [Link],
size: [Link],
heigth: [Link],
curveSegments: [Link],
bevelEnabled: [Link],
bevelOffset: [Link],
bevelThickness: [Link],
bevelSize: [Link],
bevelSegments: [Link]
})
[Link]()
[Link] = newGeometry
[Link] = 0.2
[Link]([Link])
}
}
doit()

// responsiveness
[Link]('resize', () => {
width = [Link]
height = [Link]
[Link] = width / height
[Link]()

225
[Link]

[Link]([Link], [Link])
[Link](scene, camera)
})

// renderer
const renderer = new THREE.WebGL1Renderer({ antialias: true })
[Link](width, height)
[Link]([Link]([Link], 2))

// animation
function animate() {
requestAnimationFrame(animate)

[Link](scene, camera)
}

// rendering the scene


const container = [Link]('#threejs-container')
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>

226
[Link]

Output

You can add custom fonts by using their typeface files. You can find some at
[Link] You can add different textures to the text, just like we
added to other materials.

227
[Link] – Loading 3D Models [Link]

3D models are available in many formats. You can import most of the models into [Link] and
work with them quickly. Some formats are difficult to work with, inefficient for real-time experiences,
or simply not fully supported by [Link] at this time. Let's discuss some of the standard formats
and how to load them into the [Link] file.
Note: Only a few format loaders are built-in in [Link]. For loading other format models, you
need to include their JavaScript files. You can find all the different loaders in the [Link] repo
in the three/examples/jsm/loaders directory.
For loading any model, we use these simple three steps:
1. Include [NameOfFormat][Link] in your web page.
2. Use [NameOfFormat][Link]() to load a URL.
3. Check what the response format for the callback function looks like and render the result.

OBJ Model Loader


The OBJ file defines the geometry of the material in the form of text. Many other 3D Model software
can create models in OBJ format. In Threejs, when importing an OBJ, the default material is a white
MeshPhongMaterial. You need at least one light in your scene. You can use OBJLoader to load
the models in OBJ format.

To use OBJLoader in your [Link] project, you need to add the OBJLoader JavaScript file.

<script type="text/javascript" src="../scripts/[Link]"></script>

Then, you can load the model just like you loaded the texture using .load method.

const loader = new [Link]()


[Link]('path/to/your/.obj file', (object) => {
[Link](object)
})

In this code, we use OBJLoader to load the model from a URL. Once the model is loaded, the
callback we provide is called, and we can customize the loaded mesh if you want.

MTL Model Loader


OBJ and MTL are companion formats and often used together. The MTL file defines the materials
used for the geometry in OBJ files. The MTL is also in a text-based format.

<script type="text/javascript" src="../scripts/[Link]"></script>

228
[Link]

We'll use MTLLoader and OBJLoader together in this code snippet.

const mtlLoader = new [Link]()


[Link]('/path/to/your/.mtl file', (materials) => {
[Link]()

// loading geometry
const objLoader = new [Link]()
[Link](materials)
[Link]('path/to/your/.obj file', (object) => {
mesh = object
[Link](mesh)
})
})

It loads the materials first. Then we set the materials of the OBJ file to load as the loaded material
and then load the OBJ file. It creates the mesh we needed to render an object to the scene,
customizing the mesh or material just like those in the [Link] projects.

GLTF Model Loader


A glTF file may contain one or more scenes, meshes, materials, textures, skins, skeletons, morph
targets, animations, lights, and cameras. It is the recommended format by official [Link].
[Link] and .GLTF versions of the format are well-supported by [Link]. Because glTF focuses
on runtime asset delivery, it is compact to transmit and fast to load.

<script src="../scripts/[Link]"></script>

Using the GLTFLoader object, you can import either JSON (.gltf) or binary (.glb) format.

const loader = new [Link]()


// loading model
[Link]('path/to/[Link]', (gltf) => {
[Link]([Link])
})

The scene of the imported glTF model is added to our [Link] project. The loaded model may
contain two scenes; you can specify the scene you want to import.

DRACO Loader
The DRACOLoader is used to load geometry (.drc format files) compressed with the Draco library.
Draco is an open-source library for compressing and decompressing 3D meshes and point clouds.

229
[Link]

glTF files can also be compressed using the DRACO library, and they can also be loaded using
the glTFLoader. We can configure the glTFLoader to use the DRACOLoader to decompress the
file in such cases.

<script src="../scripts/[Link]"></script>
<script src="../scripts/[Link]"></script>

Like any other model, you can easily load the .drc files using DRACOLoader. And then, you can
add Material to the geometry loaded and render the Mesh to the scene.

const loader = new [Link]()


[Link]('/scripts/draco/')

// Load a Draco geometry


[Link]('path/to/your/.drc file', (geometry) => {
const material = new [Link]({ color: 0xffffff })
const mesh = new [Link](geometry, material)
[Link](mesh)
})

This code snippet is used when you want to impoprt glTF file format that has geometry
compressed using Draco library.

const dracoLoader = new [Link]()


[Link]('/scripts/draco/')
[Link]({ type: 'js' })

// loading glTF model that uses draco library


const loader = new [Link]()
[Link](dracoLoader)
[Link]('models/monkey_compressed.glb', (gltf) => {
[Link]([Link])
})

STL Model Loader


The STL model format is widely used for rapid prototyping, 3D printing, and computer-aided
manufacturing.
STL files describe only the surface geometry of a 3D object without any representation of color,
texture, or other common 3d modeling attributes. You can add them to the callback function.

<script src="../scripts/[Link]"></script>

230
[Link]

We use the geometry from the .stl file and add material to it before adding it to the scene.

const material = new [Link]({ color: 0xaaaaaa })

const loader = new [Link]()


[Link]('path/to/your/.stl file', (geometry) => {
const mesh = new [Link](geometry, material)
[Link](mesh)
})

There are many other formats you can load into your [Link] project. The above mentioned are
the standard formats. The Loader files are well-documented and easy to use.

Troubleshooting
If you cannot load your model correctly or it is distorted, discolored, or missing entirely. These are
some troubleshooting steps mentioned in official [Link] site:
1. Check the JavaScript console for errors, and make sure you've used an onError
callback when calling .load() to log the result.

2. View the model in another application. For glTF, drag-and-drop viewers are available for
[Link] and [Link]. If the model appears correctly in one or more applications,
file a bug against [Link]. If the model cannot be shown in any application, You should
file a bug with the application used to create the model.

3. Try scaling the model up or down by a factor of 1000. Many models are scaled differently,
and large models may not appear if the camera is inside the model.

4. Try to add and position a light source. The model may be hidden in the dark.

5. Look for failed texture requests in the network tab, like


C:\\Path\To\Model\[Link]. Use paths relative to your model instead, such as
images/[Link] - this may require editing the model file in a text editor.

Asking for Help


Suppose you've gone through the troubleshooting process above, and your model still isn't
working. In that case, the right approach to asking for help gets you to a solution faster. Post a
question on the [Link] forum and, whenever possible, include your model (or a simpler model
with the same problem) in any formats you have available. Include enough information for
someone else to reproduce the issue quickly - ideally, a live demo.

231
[Link] – Libraries and Plugins [Link]

Official [Link] examples are maintained as part of the [Link] repository and always use the latest
version of [Link].
Listed here are externally developed compatible libraries and plugins for [Link].

Physics
● [Link]
● enable3d
● [Link]
● cannon-es
● [Link]

Postprocessing
In addition to the official [Link] postprocessing effects, support for some additional effects and
frameworks are available through external libraries.
● postprocessing

Intersection and Raycasting Performance


● three-mesh-bvh

File Formats
In addition to the official [Link] loaders, support for some additional formats is available through
external libraries.
● urdf-loader
● 3d-tiles-renderer-js
● WebWorker OBJLoader
● [Link]

3D Text and Layout


● troika-three-text
● three-mesh-ui

Particle Systems
● three-nebula

Inverse Kinematics
● [Link]
● fullik

232
[Link]

Game AI
● yuka
● three-pathfinding

Wrappers and Frameworks


● A-Frame
● react-three-fiber
● ECSY
It is the list maintained by the [Link] official community. Apart from these, there are many other
libraries and plugins to add beautiful effects easier.

233

Common questions

Powered by AI

Modifying the ring geometry's properties in Three.js, such as innerRadius and outerRadius, allows creative designs like creating discs with holes that can be tailored in size and segment smoothness. Adjusting phiSegments influences the circumferential resolution, enabling designers to create intricate patterns and meshes resembling complex rings or tubes, which can be used in simulations or artistic visualizations .

dat.GUI serves as an interactive graphical user interface in Three.js, allowing real-time manipulation of scene variables such as light intensity, positions, and material properties. It enhances interactivity by enabling users to experiment with these properties via sliders and color pickers, facilitating easier debugging and visualization adjustments, which is particularly useful for iterative development and learning .

Using a custom GUI like dat.GUI offers significant advantages over static code adjustments as it allows developers to adjust parameters in real-time without editing and re-compiling the code. This interactivity speeds up the testing phase, enables dynamic scene modifications, supports experimentation with lighting, material properties, and geometry configurations, and simplifies debugging by visually representing changes immediately .

Adjusting the renderer's size in a Three.js application upon window resize is crucial as it ensures the canvas dimension adapts to the new window size, maintaining aspect ratio and visual clarity. Failure to do so can result in distorted images and incorrect aspect ratios, leading to poor user experience .

The 'wireframe' property impacts the visualization of a Three.js object by rendering only the edges of the object's geometry, giving it a skeletal appearance. This is beneficial for debugging or educational purposes, allowing a clearer view of the geometry's structure. For instance, applying 'wireframe' to BoxGeometry or CircleGeometry allows the observer to see the edges and true geometry complexity .

AmbientLight illuminates a scene evenly without directionality and is better for general illumination as it affects all objects uniformly and does not cast shadows, avoiding obstructed or shadowed parts. PointLight emits omnidirectional light with a decay effect optimal for localized lighting, creating highlights and shadows. For scenes requiring uniform lighting with minimal computational overhead, AmbientLight is preferable .

Ambient Light in Three.js is unique because it illuminates the entire scene evenly, meaning it does not cast shadows. Unlike other lights that have directional properties and only illuminate objects based on angles and intensity, such as Directional or Spot lights, Ambient Light affects all objects equally .

In Three.js, SpotLight's shadow properties like shadow.camera.near, shadow.camera.far, and shadow.camera.fov define the volume within which shadows are computed. Adjusting these factors changes how far and how wide shadows are cast. This setup allows precise control over shadow quality and area, enhancing depth perception and realism in scenes by defining accurate shadow boundaries and minimizing unnecessary calculations .

In CircleGeometry, the segments property affects the smoothness of the circle; more segments result in a smoother appearance. The thetaLength property determines how complete the circle is—values less than 2 * PI create arcs instead of full circles. Together, these parameters allow developers to tailor the circle's appearance for specific scene requirements .

In Three.js, a DirectionalLight emits light in a specified direction from a distance, similar to sunlight, and illuminates objects in a parallel manner. Conversely, a SpotLight emits from a point and spreads outward in a cone shape, with configurable properties like angle and penumbra for its cone of light. Both can cast shadows, but the SpotLight provides control over the cone's angle, intensity decay, and distance .

Three.js 
1 
 
 
Three.js – Table of Contents ...............................................................................
Three.js 
2 
 
 
Using the override material property .......................................................................
Three.js 
3 
 
 
Three.js – Geometries ......................................................................................
Three.js 
4 
 
 
Three.js – Loading 3D Models ...............................................................................
Three.js 
5 
 
 
 
 
Home 
Three.js is an open-source JavaScript library that you can use to create dynamic and interactive
Three.js 
6 
 
 
All modern browsers became more powerful and more accessible directly using JavaScript. They 
have adopted W
Three.js 
7 
 
 
IEWebGL plugin, which you can get from https://github.com/iewebgl/iewebgl. You can find detailed 
informatio
Three.js 
8 
 
 
There are many ways to include Three.js in your project. You can use any of these following 
methods to get
Three.js 
9 
 
 
 
Then, you can import Three.js from the three.module.js file into your JavaScript file. 
import * as THREE

You might also like