Three.js User Manual and Guide
Three.js User Manual and Guide
js
[Link] – Introduction...................................................................................................... 6
What is [Link]? ...................................................................................................................... 6
Why use [Link]? .................................................................................................................... 6
Browser Support ...................................................................................................................... 6
1
[Link]
2
[Link]
3
[Link]
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.
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.
<script src='/path/to/[Link]'></script>
<script
src="[Link]
ript>
OR
<script
src="[Link]
>
or
8
[Link]
Then, you can import [Link] from the [Link] file into your JavaScript file.
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.
// Camera
const fov = 45 // AKA Field of View
11
[Link]
// 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)
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.
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))
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]
Adding an Object
The function add(object) is used to an object to the scene.
Removing an Object
The function remove(object) removes an object from the scene.
Children
In the [Link] return an array of all the objects in the scene, including the camera and
lights.
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.
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
17
[Link]
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]
// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)
19
[Link]
// lights
const ambientLight = new [Link](0xffffff, 0.5)
[Link](ambientLight)
// 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]
// [Link]
function removeCube() {
const allChildren = [Link]
const lastObject = allChildren[[Link] - 1]
if ([Link]) {
[Link](lastObject)
}
}
// [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)
}
22
[Link]
[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.
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:
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]
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.
[Link]('resize', () => {
// update display width and height
width = [Link]
height = [Link]
// update renderer
[Link](width, height)
[Link]([Link]([Link], 2))
[Link](scene, camera)
})
[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]
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)
}
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]
// 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)
}
31
[Link]
</script>
</body>
</html>
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.
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.
OR
Usage
First, you should initialize the object itself. It creates a widget and displays it on the screen top right
corner.
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')
[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)
}
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)
[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]
// 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)
}
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.
or
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).
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.
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]()
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]()
}
[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
// width, height
let width = [Link]
let height = [Link]
// scene
46
[Link]
// 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
})
// 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]()
}
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.
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.
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.
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.
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]
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)
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
}
}
52
[Link]
{
const planeSize = 40
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])
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]()
function render() {
55
[Link]
resizeRendererToDisplaySize(renderer)
[Link](0x262626)
// render
[Link](scene, camera)
}
[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.
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]
[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]
function main() {
const canvas = [Link]('#threejs-container')
59
[Link]
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)
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 planeSize = 40
61
[Link]
{
const color = 0xffffff
const intensity = 1
const light = new [Link](color, intensity)
[Link](0, 10, 5)
[Link](-5, 0, 0)
[Link](light)
[Link]([Link])
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]()
63
[Link]
function render() {
resizeRendererToDisplaySize(renderer)
[Link](0x262626)
[Link](scene, camera)
}
64
[Link]
[Link](0x262626)
[Link](scene, camera2)
}
requestAnimationFrame(render)
}
requestAnimationFrame(render)
}
main()
</script>
</body>
</html>
Output
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.
Update the controls for every frame. You can simply do it in your animation loop.
function animate() {
// any other animations
[Link]()
requestAnimationFrame(render)
}
[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
// 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)
// 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]()
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 }),
]
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)
}
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.
[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 & 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
const params = {
orthographicCamera: false
}
init()
animate()
function init() {
const aspect = [Link] / [Link]
74
[Link]
1000
)
[Link].z = 500
// world
// lights
75
[Link]
// renderer
//
//
[Link]('resize', onWindowResize)
createControls(perspectiveCamera)
}
function createControls(camera) {
controls = new TrackballControls(camera, [Link])
[Link] = 1.0
[Link] = 1.2
[Link] = 0.8
76
[Link]
function onWindowResize() {
const aspect = [Link] / [Link]
[Link] = aspect
[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).
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.
[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
const objects = []
let raycaster
80
[Link]
init()
animate()
function init() {
camera = new [Link](75, [Link] / window.
innerHeight, 1, 1000)
[Link].y = 10
[Link]('click', function () {
[Link]()
})
[Link]('lock', function () {
[Link] = 'none'
[Link] = 'none'
81
[Link]
})
[Link]('unlock', function () {
[Link] = 'block'
[Link] = ''
})
[Link]([Link]())
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]
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)
// floor
// vertex displacement
83
[Link]
vertex.x += [Link]() * 20 - 10
vertex.y += [Link]() * 2
vertex.z += [Link]() * 20 - 10
position = [Link]
const colorsFloor = []
// objects
position = [Link]
84
[Link]
const colorsBox = []
[Link](box)
[Link](box)
}
//
//
85
[Link]
[Link]('resize', onWindowResize)
}
function onWindowResize() {
[Link] = [Link] / [Link]
[Link]()
[Link]([Link], [Link])
}
function animate() {
requestAnimationFrame(animate)
86
[Link]
[Link](-velocity.x * delta)
[Link](-velocity.z * delta)
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.
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.
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]()
// 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)
}
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.
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].
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]
// 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]
// 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]()
// 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)
}
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]
[Link] = true
[Link] = 5
[Link] = 400
[Link] = 30
[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)
// light controls
const lightColor = {
color: [Link]()
}
const lightFolder = [Link]('Light')
[Link](lightColor, 'color').onChange(() => {
[Link]([Link])
})
[Link](light, 'intensity', 0, 1, 0.01)
[Link]()
// plane
const planeGeometry = new [Link](100, 100)
103
[Link]
// cube
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0x87ceeb
})
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[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
104
[Link]
[Link] = [Link]
[Link]([Link]([Link], 2))
// animation
function animate() {
requestAnimationFrame(animate)
[Link].x += 0.005
[Link].y += 0.01
[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.
[Link] = true
[Link] = 0.5 // default
[Link] = 500 // default
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
106
[Link]
// 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)
// light controls
const lightColor = {
color: [Link]()
}
108
[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]()
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)
}
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].
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]
// 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)
// 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]
// cube
[Link]('cube')
const geometry = new [Link](2, 2, 2)
const material = new [Link]({
color: 0x87ceeb
})
const materialFolder = [Link]('Material')
[Link](material, 'wireframe')
[Link]()
// 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)
}
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.
[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]
// Light
const ambientLight = new [Link](0xffffff, 1)
[Link](ambientLight)
[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]
})
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]
// animation
function animate() {
requestAnimationFrame(animate)
[Link].x += 0.005
[Link].y += 0.01
[Link](scene, camera)
}
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.
[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)
// circle
const geometry = new [Link]()
const material = new [Link]({
color: 0xffffff,
wireframe: true,
side: [Link]
})
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]
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)
}
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.
[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)
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 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]
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)
}
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.
131
[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] - 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)
// 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]
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)
}
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.
136
[Link]
thetaStart, thetaLength
)
[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)
// sphere
const geometry = new [Link]()
const material = new [Link]({ color: 0xffffff })
138
[Link]
[Link] = 0.7
[Link] = 0.3
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)
}
140
[Link]
Output
Cylinder Geometry
To create a cylinder in [Link], you can use the [Link].
141
[Link]
radialSegments, heightSegments,
openEnded,
thetaStart, thetaLength
)
[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
})
143
[Link]
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)
}
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.
[Link]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
146
[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 coneProps = {
radius: 1,
height: 1,
radialSegments: 8,
heightSegments: 1,
openEnded: false,
thetaStart: 0,
thetaLength: 2 * [Link]
}
const props = [Link]('Properties')
props
148
[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)
}
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.
[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 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)
}
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.
[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]
// 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 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]
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)
}
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]
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)
[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]
// GUI
const gui = new [Link]()
// sizes
let width = [Link]
let height = [Link]
// scene
const scene = new [Link]()
[Link] = new [Link](0x262626)
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
]
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)
}
Output
164
[Link]
Tetrahedron 4 [Link]
Octahedron 8 [Link]
Dodecahedron 12 [Link]
Icosahedron 20 [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] - 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]()
166
[Link]
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 dodecahedronProps = {
radius: 1,
detail: 1
}
const dodecaProps = [Link]('Dodecahedron')
dodecaProps
.add(dodecahedronProps, 'radius', 1, 50)
.step(1)
.onChange(redrawDodecahedron)
.onFinishChange(() => [Link]([Link]))
168
[Link]
function redrawDodecahedron() {
let newGeometry = new [Link](
[Link],
[Link]
)
[Link]()
[Link] = newGeometry
}
// icosahedron
const geometry3 = new [Link]()
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)
[Link](scene, camera)
}
170
[Link]
[Link]([Link])
[Link](scene, camera)
animate()
</script>
</body>
</html>
Output
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.
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.
[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]
// 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)
// 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]()
// 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)
}
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.
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
// GUI
const gui = new [Link]()
// sizes
let width = [Link]
177
[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]()
// 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)
}
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.
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.
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.
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.
180
[Link]
reflectivity,
})
In this example, you can experiment and understand the differences between
MeshLambertMaterial, MeshPhongMaterial, MeshStandardMaterial, and
MeshPhysicalMaterial.
[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
// 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)
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 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]()
})
184
[Link]
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)
}
Output
There are many other materials in [Link]. You can learn more here.
186
[Link]
color: 0xff0000,
transparent: true,
opacity: 0.7,
})
const material2 = new [Link]({ wireframe: true })
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.
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)
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]
// 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
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')
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)
}
192
[Link]
</body>
</html>
Output
Texture Mapping
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.
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.
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.
roughness map
The roughness map defines which areas are rough and that affects the reflection sharpness from
the surface.
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.
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]
// 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)
// 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]
// 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)
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)
// 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))
// animation
function animate() {
200
[Link]
requestAnimationFrame(animate)
[Link]((i) => {
//[Link].x += 0.005
[Link].y += 0.01
})
[Link]()
[Link](renderer, scene)
[Link](scene, camera)
}
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.
Note: Lines are drawn between each consecutive pair of vertices, but not between the first and
last (the line is not closed.)
// 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].
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))
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]()
})
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)
}
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))
209
[Link]
dashSize: 3,
gapSize: 2
})
[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]
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.
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]
<script src="path/to/[Link]"></script>
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.
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).
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.
215
[Link]
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.
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
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)
// 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)
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)
// camera
222
[Link]
function createMaterial() {}
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
[Link](parent)
224
[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)
}
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.
To use OBJLoader in your [Link] project, you need to add the OBJLoader JavaScript file.
Then, you can load the model just like you loaded the texture using .load method.
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.
228
[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.
<script src="../scripts/[Link]"></script>
Using the GLTFLoader object, you can import either JSON (.gltf) or binary (.glb) format.
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.
This code snippet is used when you want to impoprt glTF file format that has geometry
compressed using Draco library.
<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.
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.
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
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]
Particle Systems
● three-nebula
Inverse Kinematics
● [Link]
● fullik
232
[Link]
Game AI
● yuka
● three-pathfinding
233
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 .









