Home Data Learn Three.js - Third Edition

Learn Three.js - Third Edition

By Jos Dirksen
books-svg-icon Book
Subscription FREE
eBook + Subscription €11.99
eBook €34.99
Print + eBook €43.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 €11.99
eBook €34.99
Print + eBook €43.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
    Creating Your First 3D Scene with Three.js
About this book
WebGL makes it possible to create 3D graphics in the browser without having to use plugins such as Flash and Java. Programming WebGL, however, is difficult and complex. With Three.js, it is possible to create stunning 3D graphics in an intuitive manner using JavaScript, without having to learn WebGL. With this book, you’ll learn how to create and animate beautiful looking 3D scenes directly in your browser-utilizing the full potential of WebGL and modern browsers. It starts with the basic concepts and building blocks used in Three.js. From there on, it will expand on these subjects using extensive examples and code samples. You will learn to create, or load, from externally created models, realistic looking 3D objects using materials and textures. You’ll find out how to easily control the camera using the Three.js built-in in camera controls, which will enable you to fly or walk around the 3D scene you created. You will then use the HTML5 video and canvas elements as a material for your 3D objects and to animate your models. Finally, you will learn to use morph and skeleton-based animation, and even how to add physics, such as gravity and collision detection, to your scene. After reading this book, you’ll know everything that is required to create 3D animated graphics using Three.js.
Publication date:
August 2018
Publisher
Packt
Pages
528
ISBN
9781788833288

 

Creating Your First 3D Scene with Three.js

Over recent years, modern browsers have acquired powerful features that can be accessed directly from JavaScript. You can easily add video and audio with the HTML5 tags and create interactive components through the use of the 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. Programming 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:

  • Creating simple and complex 3D geometries
  • Creating Virtual Reality (VR) and Augmented Reality (AR) scenes
  • Animating and moving objects through a 3D scene
  • Applying textures and materials to your objects
  • Making use of different light sources to illuminate the scene
  • Loading objects from 3D-modeling software
  • Adding advanced postprocessing effects to your 3D scene
  • Working with your own custom shaders
  • Creating point clouds

With a couple of lines of JavaScript, you can create anything, from simple 3D models to photorealistic real-time scenes, as shown in the following screenshot (see it yourself by opening http://www.vill.ee/eye/ in your browser):

In this chapter, we'll directly dive into Three.js and create a couple of examples that show you how Three.js works, and which you can use to play around with. We won't dive into all the technical details yet; that's something you'll learn in the following chapters. In this chapter, we'll cover the following points:

  • The tools required to work with Three.js
  • Downloading the source code and examples used in this book
  • Creating your first Three.js scene
  • Improving the first scene with materials, lights, and animations
  • Introducing a couple of helper libraries for statistics and controlling the scene

We'll start this book with a short introduction to Three.js and then quickly move on to the first examples and code samples. Before we get started, let's quickly look at the most important browsers out there and their support for WebGL. 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. This browser has the option to render pages through the Opera servers, which often prevents JavaScript from working. Since version 8, however, the default mode of Opera Mini is to use the iOS Safari engine, which does support JavaScript and WebGL. You can still configure this browser, though, to use mini mode, which will render pages through the Opera servers and won't support WebGL in that case.

Basically, Three.js runs on any modern browser with the exception of older versions of IE. So, if you want to use an older version of IE, you've got to take an additional step. For IE 10 and older, there is the IEWebGL plugin, which you can get from https://github.com/iewebgl/iewebgl. This plugin is installed inside IE 10 and older versions and enables WebGL support for those browsers.

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 mostly 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'll show how to use the CSS 3D browser in Chapter 7, Points and Sprites.

In this chapter, you'll directly create your first 3D scene and will be able to run this in any of the browsers mentioned previously. We won't introduce too many complex Three.js features yet, but, at the end of this chapter, you'll have created the Three.js scene you can see in the following screenshot:

59 FPS (47-60)

For this first scene, you'll learn about the basics of Three.js and also create your first animation. Before you start your work on this example, in the next couple of sections, we'll first look at the tools you need to easily work with Three.js and how you can download the examples shown in this book.

 

Requirements for using Three.js

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 JavaScript editors, which I've used extensively over the last couple of years on 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/.
  • WebStorm: This editor from the JetBrains guys has 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 systems) 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 layout 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 multiple-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, 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 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.

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

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

I mentioned that most modern web browsers support WebGL and can be used to run Three.js examples. I usually run my code in Chrome. The reason is that most often, Chrome has the best support and performance for WebGL and it has a really great JavaScript debugger. With this debugger, which is shown in the following screenshot, you can quickly pinpoint problems, for instance, using breakpoints and console output. This is exemplified in the following screenshot. Throughout this book, I'll give you pointers on debugger usage and other debugging tips and tricks:

60 FPS (0-60)

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 can be accessed from GitHub (https://github.com/). GitHub is an online Git-based repository that you can use to store, access, and version source code. There are a couple of ways that you can get the sources for yourself:

  • Clone the Git repository
  • Download and extract the archive

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

Using Git to clone the repository

Git is an open source distributed version control system that I used to create and version all the examples in this book. For this, I used GitHub, a free, online Git repository. You can browse this repository from this link: https://github.com/josdirksen/learning-threejs-third.

To get all the examples, you can clone this repository using the git command-line tool. To do this, you first need to download a Git client for your operating system. For most modern operating systems, a client can be downloaded from http://git-scm.com. After installing Git, you can use this to get a clone of 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 command:

    git clone https://github.com/josdirksen/learning-threejs-third

This will start downloading all the examples, as shown in the following screenshot:

The learning-threejs-third directory will now contain all the examples that are used 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/josdirksen/learning-threejs-third in a browser and click on the Clone or download button on the right-hand side. This will give you the option to download all the sources in a single ZIP file:

Extract this to a directory of your choice, and you'll have all the examples available.

Downloading the example code: 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.

Testing the examples

Now that you've downloaded or cloned the source code, let's do a quick check to see whether everything is working and make you familiar with the directory structure. The code and examples are organized per chapter. There are two different ways of viewing examples. You can either open the extracted or cloned folder in a browser directly and look at and run a specific example, or you can install a local web server. This first approach will work for most of the basic examples, but when we start loading external resources, such as models or texture images, just opening the HTML file isn't enough. In this case, we need a local web server to make sure the external resources are loaded correctly. In the following section, we explain a couple of different ways you can set up a simple local web server for testing. If you can't set up a local web server but use Chrome or Firefox, we also provide an explanation on how to disable certain security features so that you can even test without a local web server.

Setting up a local web server is very easy depending on what you've already got installed. In here, we list a couple of examples on how to do this. There are many different ways of doing this, depending on what you've already got installed on your system.

Python-based web servers should work on most Unix/macOS systems

Most Unix/Linux/macOS systems already have Python installed. On those systems, you can very easily start a local web server:

     > python -m SimpleHTTPServer
     Serving HTTP on 0.0.0.0 port 8000 ...

Do this in the directory where you checked out / downloaded the source code.

Npm-based web server if you've worked with Node.js

If you've already done some work with Node.js, there is good chance you've got npm installed. With npm, you have two simple options to set up a quick local web server for testing. The first option uses the http-server module, as follows:

     > npm install -g http-server
     > http-server
    Starting up http-server, serving ./ on port: 8080
    Hit CTRL-C to stop the server

Alternatively, you can also use the simple-http-server option, as follows:

    > npm install -g simple-http-server
    > nserver
    simple-http-server Now Serving: /Users/jos/git/Physijs at http://localhost:8000/

A disadvantage of this second approach, however, is that it doesn't automatically show directory listings when browsing the sources, whereas the first approach does.

Portable version Mongoose for macOS and/or Windows

If you haven't got Python or npm installed, there is a simple, portable web server, named Mongoose, that you can use. First, download the binaries for your specific platform from https://code.google.com/p/mongoose/downloads/list. If you are using Windows, copy it to the directory containing the examples and double-click on the executable to start a web browser serving the directory it is started in.

For other operating systems, you must also copy the executable to the target directory, but instead of double-clicking on the executable, you have to launch it from the command line:

In both cases, a local web server will be started on port 8080. The following screenshot shows the output when you open a browser to a locally running Mongoose server:

All the examples are in the src folder. By just clicking on a chapter in this folder, we can show and access all the examples for that specific chapter. If we discuss an example in this book, we'll refer to the specific name and folder so that you can directly test and play around with the code.

Running from the filesystem by disabling security exceptions in Firefox and Chrome

If you use Chrome to run the examples, there is a way to disable some security settings so that you can use Chrome to view the examples without requiring a web server. Note that you shouldn't do this on a browser you use on the internet since it can leave you open to all kinds of malicious code. To do this, you have to start Chrome in the following way:

  • For Windows, you call the following:
 chrome.exe --disable-web-security  
  • On Linux, do the following:
 google-chrome --disable-web-security
  • And on macOS, you disable the settings by starting Chrome like this:
 open -a "Google Chrome" --args --disable-web-security  

When you start Chrome this way, you can access all the examples directly from the local filesystem.

For Firefox users, we need to take a couple of different steps. Open Firefox and, in the URL bar, type about:config. This is what you'll see:

Warning window

On this screen, click on the I'll be careful, I promise! button. This will show you all the available properties you can use to fine-tune Firefox. In the search box on this screen, type in security.fileuri.strict_origin_policy and change its value to false, just as we did in the following screenshot:

At this point, you can also use Firefox to directly run the examples provided in this book. Now that you've either got a web server installed, or disabled the necessary security settings, it is time to start creating our first Three.js scene.

             
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
Latest Reviews (7 reviews total)
was an outstanding book..
contains useful information
This book is useful for beginners like me. But if would have been better if it contained a description of GLTF loading.
Recommended For You
Learn Three.js - Third Edition
Unlock this book and the full library FREE for 7 days
Start now