Home Web Development Learn Three.js - Fourth Edition

Learn Three.js - Fourth Edition

By Jos Dirksen
books-svg-icon Book
Subscription FREE
eBook + Subscription €14.99
eBook €29.99
Print + eBook €37.99
READ FOR FREE Free Trial for 7 days. €11.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
READ FOR FREE Free Trial for 7 days. €11.99 p/m after trial. Cancel Anytime! BUY NOW BUY NOW BUY NOW
Subscription FREE
eBook + Subscription €14.99
eBook €29.99
Print + eBook €37.99
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
  1. Free Chapter
    Chapter 1: Creating Your First 3D Scene with Three.js
About this book
Three.js has become the industry standard for creating stunning 3D WebGL content. In this edition, you’ll learn about all the features of Three.js and understand how to integrate it with the newest physics engines. You'll also develop a strong grip on creating and animating immersive 3D scenes directly in your browser, reaping the full potential of WebGL and modern browsers. The book starts with the basic concepts and building blocks used in Three.js and helps you explore these essential topics in detail through extensive examples and code samples. You'll learn how to create realistic-looking 3D objects using textures and materials and how to load existing models from an external source. Next, you'll understand how to control the camera using the Three.js built-in camera controls, which will enable you to fly or walk around the 3D scene you've created. Later chapters will cover the use of HTML5 video and canvas elements as materials for your 3D objects to animate your models. You’ll learn how to use morph targets and skeleton-based animation, before understanding how to add physics, such as gravity and collision detection, to your scene. Finally, you’ll master combining Blender with Three.js and creating VR and AR scenes. By the end of this book, you'll be well-equipped to create 3D-animated graphics using Three.js.
Publication date:
February 2023
Publisher
Packt
Pages
554
ISBN
9781803233871

 

Creating Your First 3D Scene with Three.js

In recent years, modern browsers have acquired powerful features that can be accessed directly from JavaScript. You can easily add video and audio with HTML5 tags and create interactive components through the use of HTML5 Canvas. Together with HTML5, modern browsers also support WebGL. With WebGL, you can directly make use of the processing resources of your graphics card and create high-performance 2D and 3D computer graphics. Using WebGL directly from JavaScript to create and animate 3D scenes is a very complex, verbose, and error-prone process. Three.js is a library that makes this a lot easier. The following list shows some of the things that are very easy to do with Three.js:

  • Create simple and complex 3D geometries and render them in any browser
  • Animate and move objects through a 3D scene
  • Apply textures and materials to your objects
  • Use different light sources to illuminate the scene
  • Use models from 3D modeling software and export generated models into these programs
  • Add advanced post-processing effects to your 3D scene
  • Create and work with custom shaders
  • Create, visualize, and animate point clouds
  • Create virtual reality (VR) and augmented reality (AR) scenes

With a couple of lines of JavaScript (or TypeScript, as we’ll see later in this book), you can create anything, from simple 3D models to photorealistic scenes, all of which are rendered in real time in the browser. For instance, Figure 1.1 shows an example of what can be done with Three.js (you can see the animation for yourself by opening https://threejs.org/examples/webgl_animation_keyframes.html in your browser):

Figure 1.1 – Three.js rendered and animated scene

Figure 1.1 – Three.js rendered and animated scene

In this chapter, we’ll directly dive into Three.js and create a couple of examples that will show you how Three.js works, and that you can use to play around with and get to know Three.js a little bit. We won’t dive into all the technical details yet; you'll learn about those in the following chapters. By the end of this chapter, you’ll be able to create a scene, and run and explore all the examples in this book.

We’ll start this book with a short introduction to Three.js and then quickly move on to the first few examples and code samples. Before we get started, let’s quickly look at the most important browsers out there and their support for WebGL (and WebGPU).

Note

All modern browsers on desktop, as well as on mobile, currently support WebGL. Older versions of IE (those before version 11) won’t be able to run WebGL-based applications. On mobile, most browsers support WebGL. So, with WebGL, you can create interactive 3D visualizations that run very well on desktops, as well as on mobile devices.

In this book, we’ll focus on the WebGL-based renderer provided by Three.js. There is, however, also a CSS 3D-based renderer, which provides an easy API to create CSS 3D-based 3D scenes. A big advantage of using a CSS 3D-based approach is that this standard is supported on all mobile and desktop browsers and allows you to render HTML elements in a 3D space. We won’t go into the details of this browser but will show an example in Chapter 7, Points and Sprites.

Besides WebGL, a new standard for using the GPU to render in your browser called WebGPU is being developed, which will provide even better performance than WebGL and, in the future, become the new standard. When you use Three.js, you don’t have to worry about this change. Three.js already partly supports WebGPU and as that standard matures, so will the support of this standard in Three.js. So, everything you create with Three.js will also work out of the box with WebGPU.

In this first chapter, you’ll directly create a 3D scene and be able to run it on a desktop or mobile device. We’ll explain the core concepts of Three.js, and if there are more advanced topics, we’ll mention in what chapter we’ll explain these in more detail. In this chapter, we’ll create two different scenes. The first one will show a basic geometry rendered in Three.js, as shown in the following figure:

Figure 1.2 – Default geometries rendered

Figure 1.2 – Default geometries rendered

After that, we’ll also quickly show you how you can load external models, and how easy it is to create realistic-looking scenes. The result of the second example will look like this:

Figure 1.3 – Rendering an externally loaded model

Figure 1.3 – Rendering an externally loaded model

Before you start working on these examples, in the next couple of sections, we’ll look at the tools you need to easily work with Three.js and how you can download the examples shown in this book.

In this chapter, we’ll cover the following topics:

  • Requirements for using Three.js
  • Downloading the source code and examples used in this book
  • Testing and experimenting with the examples
  • Rendering and viewing a 3D object
  • Introducing a couple of helper libraries for statistics and controlling the scene
 

Technical requirements

Three.js is a JavaScript library, so all you need to create Three.js WebGL applications is a text editor and one of the supported browsers to render the results. I would like to recommend the following text editors, which I’ve used extensively over the last couple of years for various projects:

  • Visual Studio Code: This free editor from Microsoft runs on all major platforms and provides great syntax highlighting and smart completion based on types, function definitions, and imported libraries. It provides a very clean interface and is great for working on JavaScript projects. It can be downloaded from here: https://code.visualstudio.com/. If you don’t want to download this editor, you can also just navigate to https://vscode.dev/, which will launch an editor directly in your browser, from which you can connect to a GitHub repository or access directories on your local filesystem.
  • WebStorm: This editor from JetBrains offers great support for editing JavaScript. It supports code completion, automatic deployment, and JavaScript debugging, directly from the editor. Besides this, WebStorm has excellent GitHub (and other version control system) support. You can download a trial edition from http://www.jetbrains.com/webstorm/.
  • Notepad++: Notepad++ is a general-purpose editor that supports code highlighting for a wide range of programming languages. It can easily lay out and format JavaScript. Note that Notepad++ is only for Windows. You can download Notepad++ from http://notepad-plus-plus.org/.
  • Sublime Text Editor: Sublime is a great editor that offers very good support for editing JavaScript. Besides this, it provides many very helpful selections (such as multi-line select) and edit options, which, once you get used to them, provide a really good JavaScript-editing environment. Sublime can also be tested for free and can be downloaded from http://www.sublimetext.com/.

Even if you don’t use any of these editors, there are a lot of editors available, both open source and commercial, that you can use to edit JavaScript and create your Three.js projects, since all you need is the ability to edit text. An interesting project you might want to look at is AWS Cloud9 (http://c9.io). This is a cloud-based JavaScript editor that can be connected to a GitHub account. This way, you can directly access all the source code and examples from this book and experiment with them.

Note

Besides these text-based editors, which you can use to edit and experiment with the sources from this book, Three.js currently also provides an online editor.

With this editor, which you can find at http://threejs.org/editor/, you can create Three.js scenes using a graphical approach.

I suggest picking up Visual Studio Code. It is a very lightweight editor with great support for JavaScript and has several other extensions that make writing JavaScript applications easier.

Earlier, I mentioned that most modern web browsers support WebGL and can be used to run Three.js examples. I usually run my code in Firefox. The reason is that, often, Firefox has the best support and performance for WebGL and it has a great JavaScript debugger. With this debugger, as shown in the following screenshot, you can quickly pinpoint problems using, for instance, breakpoints and console output:

Figure 1.4 – Firefox debugger

Figure 1.4 – Firefox debugger

Note

All the examples in this book will work just as well with Chrome as they do with Firefox. So, if that’s your browser of choice, you can, of course, use that one instead.

Throughout this book, I’ll give you pointers on debugger usage and other debugging tips and tricks. That’s enough by way of an introduction for now; let’s get the source code and start with the first scene.

Getting the source code

All the code for this book is available on GitHub (https://github.com/PacktPublishing/Learn-Three.js-Fourth-edition). GitHub is a site that hosts Git repositories. You can use these to store, access, and version source code. There are a couple of ways that you can get the sources for yourself. You can do either of the following:

  • Clone the Git repository. This means you use the git command-line tool to get the latest version of the sources for this book.
  • Download and extract an archive from GitHub, which contains everything.

In the following two subsections, we’ll explore these options in a bit more detail.

Using git to clone the repository

One way to get all the examples is to clone this repository using the git command-line tool. To do this, you need to download a Git client for your operating system. If you’ve got an up-to-date operating system, you probably already have Git installed. You can quickly check this by running the following in a terminal:

$ git --version
git version 2.30.1 (Apple Git-130)

If the command isn’t installed yet, you can get a client and instructions on how to install it from here: http://git-scm.com. After installing Git, you can use the git command-line tool to clone this book’s repository. Open a command prompt and go to the directory where you want to download the sources. In that directory, run the following:

$ git clone https://github.com/PacktPublishing/Learn-Three.js-Fourth-edition.
git clone git@github.com:PacktPublishing/Learn-Three.js-Fourth-edition.git
Cloning into 'learning-threejs-fourth'...
remote: Enumerating objects: 96, done.
remote: Counting objects: 100% (96/96), done.
remote: Compressing objects: 100% (85/85), done.
fetch-pack: unexpected disconnect while reading sideband packet
...

After doing this, all the source code will be downloaded into the learning-threejs-fourth directory. From that directory, you can run all the examples explained throughout this book.

Downloading and extracting the archive

If you don’t want to use git to download the sources directly from GitHub, you can also download an archive. Open https://github.com/PacktPublishing/Learn-Three.js-Fourth-edition in a browser and click on the Code button on the right-hand side. This will give you the option to download all the sources in a single ZIP file by clicking on the Download ZIP option:

Figure 1.5 – Downloading the archive from GitHub

Figure 1.5 – Downloading the archive from GitHub

After extracting this to a directory of your choice, all the examples will become available.

Note

You can also download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.

Now that you’ve downloaded or cloned the source code, let’s quickly check whether everything is working and familiarize you with the directory structure.

 

Testing and experimenting with the examples

The code and examples are organized per chapter and, with the examples, we will provide a simple integrated server that you can use to access all the examples. To get this server up and running, we need to install Node.js and npm. These tools are used to manage JavaScript packages and build JavaScript applications and make it easier to modularize our Three.js code and integrate existing JavaScript libraries.

To install these two tools, go to https://nodejs.org/en/download/ and select the appropriate installer for your operating system. Once installed, open a terminal and check whether everything is working. On my machine, the following versions are being used:

$ npm --version
8.3.1
$ node --version
v16.14.0

Once these tools have been installed, we need to perform a few steps to get all the externally needed dependencies before we can build and access the examples:

  1. First, we need to download the external libraries used in the examples. For instance, Three.js is one of the dependencies we need to download.

To download all the dependencies, run the following command in the directory where you downloaded or extracted all the examples:

$ npm install
added 570 packages, and audited 571 packages in 21s

The preceding command will start downloading all the required JavaScript libraries and store these in the node_modules folder.

  1. Next, we need to build the examples. Doing so will combine our source code and the external libraries into a single file, which we can show in the browser.

To build the examples using npm, use the following command:

$ npm run build
> ltjs-fourth@1.0.0 build
> webpack build
...

Note that you only have to run the two preceding commands once.

  1. With that, all the examples will have been built and are ready for you to explore. To open these examples, you need a web server. To start a server, simply run the following command:
    $ npm run serve
    > ltjs-fourth@1.0.0 serve
    > webpack serve –open
    <i> [webpack-dev-server] Project is running at:
    <i> [webpack-dev-server] Loopback: http://localhost:8080/
    <i> [webpack-dev-server] On Your Network (Ipv4): http://192.168.68.144:8080/
    <i> [webpack-dev-server] On Your Network (Ipv6): http://[fe80::1]:8080/

At this point, you’ll probably notice that npm has already opened your default browser and shows the content of http://localhost:8080 (if this isn’t the case, just open your browser of choice and navigate to http://localhost:8080). You’ll be presented with an overview of all the chapters. In each of these subfolders, you’ll find the examples that are explained in that chapter:

Figure 1.6 – Overview of all the chapters and examples

Figure 1.6 – Overview of all the chapters and examples

One very interesting feature of this server is that we can now see the changes we make to the source code immediately reflected in the browser. If you have started the server by running npm run serve, open up the chapter-01/geometries.js example from the sources you’ve downloaded in your editor and change something; you’ll see that this is also changed at the same time in your browser after you have saved the change. This makes testing changes and fine-tuning colors and lights much easier. If you open the chapter-01/geometries.js file in your code editor, and you open the http://localhost:8080/chapter-01/geometries.html example in your browser, you can see this in action. In your editor, change the color of the cube. To do so, find the following code:

initScene(props)(({ scene, camera, renderer, orbitControls }) => {
  const geometry = new THREE.BoxGeometry();
  const cubeMaterial = new THREE.MeshPhongMaterial({
    color: 0xFF0000,
  });

Change it to the following:

initScene(props)(({ scene, camera, renderer, orbitControls }) => {
  const geometry = new THREE.BoxGeometry();
  const cubeMaterial = new THREE.MeshPhongMaterial({
    color: 0x0000FF,
  });

Now, when you save the file, you’ll immediately see that the color of the cube in the browser changes, without you having to refresh the browser or do anything else.

Note

The setup we’re working with in this book is one of many different approaches you can use to develop web applications. Alternatively, you can include Three.js (and other libraries) directly in your HTML file or use an approach with import-maps, as is done with the example on the Three.js website. All of these have advantages and disadvantages. For this book, we’ve chosen an approach that makes it easy to experiment with the sources and get direct feedback in the browser, and closely resembles how these kinds of applications are built normally.

A good starting point to understand how everything works together is by looking at the HTML file that we opened in the browser.

       
About the Author
  • Jos Dirksen

    Jos Dirksen has worked as a software developer and architect for almost two decades. He has a lot of experience in many technologies, ranging from backend technologies, such as Java and Scala, to frontend development using HTML5, CSS, JavaScript, and Typescript. Besides working with these technologies, Jos regularly speaks at conferences and likes to write about new and interesting technologies on his blog. He also likes to experiment with new technologies and see how they can best be used to create beautiful data visualizations. Previously, Jos has worked in many different roles in the private and public sectors, ranging from private companies such as ING, ASML, Malmberg, and Philips to organizations in the public sector, such as the Department of Defense and the Port of Rotterdam.

    Browse publications by this author
Learn Three.js - Fourth Edition
Unlock this book and the full library FREE for 7 days
Start now