Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Three.js Cookbook
Three.js Cookbook

Three.js Cookbook: Over 80 shortcuts, solutions, and recipes that allow you to create the most stunning visualizations and 3D scenes using the Three.js library

eBook
$9.99 $32.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Three.js Cookbook

Chapter 2. Geometries and Meshes

In this chapter, we'll cover the following recipes:

  • Rotating an object around its own axis
  • Rotating an object around a point in space
  • Informing Three.js about updates
  • Working with a large number of objects
  • Creating geometries from height maps
  • Pointing an object to another object
  • Writing text in 3D
  • Rendering 3D formulas as 3D geometries
  • Extending Three.js with a custom geometry object
  • Creating a spline curve between two points
  • Creating and exporting a model from Blender
  • Using OBJMTLLoader with multiple materials
  • Applying matrix transformations

Introduction

Three.js comes with a large number of geometries that you can use out of the box. In this chapter, we'll show you some recipes that explain how you can transform these standard geometries. Besides that, we'll also show you how to create your own custom geometries and load geometries from external sources.

Note

You can access all of the example code within all recipes in this cookbook from the GitHub repository created at https://github.com/josdirksen/threejs-cookbook.

Rotating an object around its own axis

There are many ways in which you can change the appearance of a mesh. For example, you can change its position, scale, or material. Often, you'll also need to change the rotation of THREE.Mesh. In this first recipe on rotation, we'll show you the simplest way to rotate an arbitrary mesh.

Getting ready

To rotate a mesh, we first need to create a scene that contains an object you can rotate. For this recipe, we provide an example, 02.01-rotate-around-axis.html, that you can open in your browser. When you open this recipe, you'll see something similar to the following screenshot in your browser:

Getting ready

In this demo, you can see a 3D cube slowly rotating around its axis. Using the control GUI in the upper-right corner, you can change the speed at which the object rotates.

How to do it...

To rotate the cube from this example around its axis like we showed you in the previous screenshot, you have to take a couple of steps:

  1. For the first step in this recipe...

Rotating an object around a point in space

When you rotate an object using its rotate property, the object is rotated around its own center. In some scenarios, though, you might want to rotate an object around a different object. For instance, when modeling the solar system, you want to rotate the moon around the earth. In this recipe, we'll explain how you can set up Three.js objects in such a way that you can rotate them around one another or any point in space.

Getting ready

For this recipe, we've also provided an example you can experiment with. To load this example, just open 02.02-rotate-around-point-in-space.html in a browser. When you open this file, you'll see something similar to the following screenshot:

Getting ready

With the controls on the right-hand side, you can rotate various objects around. By changing the rotationSpeedX, rotationSpeedY, and rotationSpeedZ properties, you can rotate the red box around the center of the sphere.

Tip

To best demonstrate the rotation of an object...

Informing Three.js about updates

If you've worked a bit longer with Three.js, you'll probably have noticed that sometimes, it seems that changes you make to a certain geometry doesn't always result in a change onscreen. This is because for performance reasons, Three.js caches some objects (such as the vertices and faces of a geometry) and doesn't automatically detect updates. For these kinds of changes, you'll have to explicitly inform Three.js that something has changed. In this recipe, we'll show you what properties of a geometry are cached and require explicit notification to Three.js to be updated. These properties are:

  • geometry.vertices
  • geometry.faces
  • geometry.morphTargets
  • geometry.faceVertexUvs
  • geometry.faces[i].normal and geometry.vertices[i].normal
  • geometry.faces[i].color and geometry.vertices[i].color
  • geometry.vertices[i].tangent
  • geometry.lineDistances

Getting ready

An example is available that allows you to change two properties that require an explicit update...

Working with a large number of objects

If you have scenes with large numbers of objects, you will start noticing some performance issues. Each of the meshes you create and add to the scene will need to be managed by Three.js, which will cause slowdowns when you're working with thousands of objects. In this recipe, we'll show you how to merge objects together to improve performance.

Getting ready

There are no additional libraries or resources required to merge objects together. We've prepared an example that shows you the difference in performance when using separate objects compared to a merged object. When you open up the 02.05-handle-large-number-of-object.html example, you can experiment with the different approaches.

You will see something similar to the following screenshot:

Getting ready

In the preceding screenshot, you can see that with a merged object approach, we still get 60 fps when working with 120,000 objects.

How to do it...

Merging objects in Three.js is very easy. The following...

Creating geometries from height maps

With Three.js, it is easy to create your own geometries. For this recipe, we're going to show you how to create your own geometry based on a terrain height map.

Getting ready

To convert a height map into a 3D geometry, we first need to have a height map. In the source files provided with this book, you can find a height map for a portion of the Grand Canyon. The following image shows you what this looks like:

Getting ready

If you're familiar with the Grand Canyon, you'll probably recognize the distinct shape. The final result we'll have at the end of this recipe can be viewed by opening up the 02.06-create-terrain-from-heightmap.html file in your browser. You'll see something similar to the following screenshot:

Getting ready

How to do it...

To create a heightmap-based geometry, you need to perform these steps:

  1. Before we look at the required Three.js code, we first need to load the image and set some properties that determine the final size and height of the...

Introduction


Three.js comes with a large number of geometries that you can use out of the box. In this chapter, we'll show you some recipes that explain how you can transform these standard geometries. Besides that, we'll also show you how to create your own custom geometries and load geometries from external sources.

Note

You can access all of the example code within all recipes in this cookbook from the GitHub repository created at https://github.com/josdirksen/threejs-cookbook.

Rotating an object around its own axis


There are many ways in which you can change the appearance of a mesh. For example, you can change its position, scale, or material. Often, you'll also need to change the rotation of THREE.Mesh. In this first recipe on rotation, we'll show you the simplest way to rotate an arbitrary mesh.

Getting ready

To rotate a mesh, we first need to create a scene that contains an object you can rotate. For this recipe, we provide an example, 02.01-rotate-around-axis.html, that you can open in your browser. When you open this recipe, you'll see something similar to the following screenshot in your browser:

In this demo, you can see a 3D cube slowly rotating around its axis. Using the control GUI in the upper-right corner, you can change the speed at which the object rotates.

How to do it...

To rotate the cube from this example around its axis like we showed you in the previous screenshot, you have to take a couple of steps:

  1. For the first step in this recipe, we'll set...

Rotating an object around a point in space


When you rotate an object using its rotate property, the object is rotated around its own center. In some scenarios, though, you might want to rotate an object around a different object. For instance, when modeling the solar system, you want to rotate the moon around the earth. In this recipe, we'll explain how you can set up Three.js objects in such a way that you can rotate them around one another or any point in space.

Getting ready

For this recipe, we've also provided an example you can experiment with. To load this example, just open 02.02-rotate-around-point-in-space.html in a browser. When you open this file, you'll see something similar to the following screenshot:

With the controls on the right-hand side, you can rotate various objects around. By changing the rotationSpeedX, rotationSpeedY, and rotationSpeedZ properties, you can rotate the red box around the center of the sphere.

Tip

To best demonstrate the rotation of an object around another...

Informing Three.js about updates


If you've worked a bit longer with Three.js, you'll probably have noticed that sometimes, it seems that changes you make to a certain geometry doesn't always result in a change onscreen. This is because for performance reasons, Three.js caches some objects (such as the vertices and faces of a geometry) and doesn't automatically detect updates. For these kinds of changes, you'll have to explicitly inform Three.js that something has changed. In this recipe, we'll show you what properties of a geometry are cached and require explicit notification to Three.js to be updated. These properties are:

  • geometry.vertices

  • geometry.faces

  • geometry.morphTargets

  • geometry.faceVertexUvs

  • geometry.faces[i].normal and geometry.vertices[i].normal

  • geometry.faces[i].color and geometry.vertices[i].color

  • geometry.vertices[i].tangent

  • geometry.lineDistances

Getting ready

An example is available that allows you to change two properties that require an explicit update: face colors...

Working with a large number of objects


If you have scenes with large numbers of objects, you will start noticing some performance issues. Each of the meshes you create and add to the scene will need to be managed by Three.js, which will cause slowdowns when you're working with thousands of objects. In this recipe, we'll show you how to merge objects together to improve performance.

Getting ready

There are no additional libraries or resources required to merge objects together. We've prepared an example that shows you the difference in performance when using separate objects compared to a merged object. When you open up the 02.05-handle-large-number-of-object.html example, you can experiment with the different approaches.

You will see something similar to the following screenshot:

In the preceding screenshot, you can see that with a merged object approach, we still get 60 fps when working with 120,000 objects.

How to do it...

Merging objects in Three.js is very easy. The following code snippet...

Creating geometries from height maps


With Three.js, it is easy to create your own geometries. For this recipe, we're going to show you how to create your own geometry based on a terrain height map.

Getting ready

To convert a height map into a 3D geometry, we first need to have a height map. In the source files provided with this book, you can find a height map for a portion of the Grand Canyon. The following image shows you what this looks like:

If you're familiar with the Grand Canyon, you'll probably recognize the distinct shape. The final result we'll have at the end of this recipe can be viewed by opening up the 02.06-create-terrain-from-heightmap.html file in your browser. You'll see something similar to the following screenshot:

How to do it...

To create a heightmap-based geometry, you need to perform these steps:

  1. Before we look at the required Three.js code, we first need to load the image and set some properties that determine the final size and height of the geometry. This can be done...

Pointing an object to another object


A common requirement for many games is that cameras and other objects follow each other or be aligned to one another. Three.js has standard support for this using the lookAt function. In this recipe, you'll learn how you can use the lookAt function to point an object to look at another object.

Getting ready

The example for this recipe can be found in the sources for this book. If you open 02.07-point-object-to-another.html in your browser, you see something similar to the following screenshot:

With the menu, you can point the large blue rectangle to look at any of the other meshes in the scene.

How to do it...

Creating the lookAt functionality is actually very simple. When you add THREE.Mesh to the scene, you can just call its lookAt function and point it to the position it should turn to. For the example provided for this recipe, this is done as follows:

  control = new function() {
    this.lookAtCube = function() {
      cube.lookAt(boxMesh.position);
 ...

Writing text in 3D


A cool feature of Three.js is that it allows you to write text in 3D. With a couple of simple steps, you can use any text, even with font support, as a 3D object in your scene. This recipe shows you how to create 3D text and explains the different configuration options available to style the result.

Getting ready

To work with 3D text, we need to include some additional JavaScript in our pages. Three.js provides a number of fonts you can use, and they are provided as individual JavaScript files. To add all the available fonts, include the following scripts:

  <script src="../assets/fonts/gentilis_bold.typeface.js">
  </script>
  <script src="../assets/fonts/gentilis_regular.typeface.js">
  </script>
  <script src="../assets/fonts/optimer_bold.typeface.js"></script>
  <script src="../assets/fonts/optimer_regular.typeface.js">
  </script>
  <script src="../assets/fonts/helvetiker_bold.typeface.js">
  </script>
  &lt...
Left arrow icon Right arrow icon

Description

This book is ideal for anyone who already knows JavaScript and would like to get a broad understanding of Three.js quickly, or for those of you who have a basic grasp of using Three.js but want to really make an impact with your 3D visualizations by learning its advanced features. To apply the recipes in this book you don’t need to know anything about WebGL; all you need is some general knowledge about JavaScript and HTML.

What you will learn

  • Create a standard HTML skeleton and advanced features such as keyboard controls, drag and drop support, WebGL detection, and loading resources
  • Build and transform Three.js geometries using simple properties and advanced matrix transformations
  • Enhance the look of your scene using Three.js materials, texture maps, and dynamic textures
  • Apply realistic lighting and shadows to the 3D objects you have created
  • Animate particle systems created from scratch or from existing geometries
  • Work with animations, advanced physics, and collision detection

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 30, 2015
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781783981199
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jan 30, 2015
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781783981199
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 142.97
Game Development with Three.js
$32.99
Learning Three.js: The JavaScript 3D Library for WebGL - Second Edition
$54.99
Three.js Cookbook
$54.99
Total $ 142.97 Stars icon
Banner background image

Table of Contents

8 Chapters
1. Getting Started Chevron down icon Chevron up icon
2. Geometries and Meshes Chevron down icon Chevron up icon
3. Working with the Camera Chevron down icon Chevron up icon
4. Materials and Textures Chevron down icon Chevron up icon
5. Lights and Custom Shaders Chevron down icon Chevron up icon
6. Point Clouds and Postprocessing Chevron down icon Chevron up icon
7. Animation and Physics Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(8 Ratings)
5 star 50%
4 star 25%
3 star 0%
2 star 25%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Michael Jun 16, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is the 3rd book on Three.js by this author. When I used it was the most recent but I see there is another one now. This publisher has several formats for books. The author has been basically working his way threw the formats for the same subject. This is not bad. I suspect that each version is an improvement over the last one. This book was fairly well polished and obviously not the first one on the subject by this author.I rather liked this format. I needed quick well targeted examples to complete a school project. I found them in this book and took many code snippets (properly credited of course).All the examples however assume that there is nothing on the page but the canvas that is running WebGL/Three.js. I needed just a window and had other text on the page to document my project. I looked several places and could not find a solution. I wrote the author about this omission. In a couple of days he gave me back the example that I needed. I had been making the problem much more complicated than necessary. I hope he included it in his next installment.Again, I rather like the cookbook format and will look for them again from this publisher.
Amazon Verified review Amazon
Keith Hoffman Mar 03, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Awesome book! Anyone using Javascript wanting 3D technology to be their next step must have this book.
Amazon Verified review Amazon
Pravin Asar May 08, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
In the book “Three.js Cookbook”, I found the organization and gradual progression from basics such as getting started to more advanced recipes for development; such as geometries, meshes, camera and lights, animation, etc.; using Three.js library very useful. No doubt Three.js is wonderful and reduces a steep learning curve with WebGL. Some of those who (includes myself) did graphics programming using OpenGL, will definitely appreciate the Three.js library.This books assumes, you have background in some background in Three.JS and WebGL. If you are looking to learn Three.JS, please read comprehensive guide "Learning Three.js: The JavaScript 3D Library for WebGL".In e-book I reviewed, I found many nice colorful illustrations and example code. Best of all, code examples I downloaded, each one works well.You can do some interactions (such as camera, lights, animation examples, etc.) with these examples. The examples themselves usually provide widgets that allow to change scene parameters and see what happens.You'll quickly learn how to perform some common tasks using these recipes. Each "recipe" exposes you to solve a particular problem or help you learn a new facet of Three.js. The gradual built-up of each "recipe" leads to another that can build on it. Ultimately combination of these recipes can help you build production ready applications.Overall, the book has met my expectations, could serve as reference as how-to guide. Has plenty of information, to dive right into real world WebGL development with Three.js.Mastering graphics API is not always easy, but I would say this book provides good head start. Many many solutions, tips and recipes
Amazon Verified review Amazon
CCrum Nov 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
An excellent supplement to other works by this author.
Amazon Verified review Amazon
Hammink John Feb 08, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
My original review was not early as glowing as my update now is! There would appear to be some missing instructions at the beginning of the book that one must do to get the examples running (copying /libs directory, updating path/ensuring webGL compatibility of browser) that might seem pretty obvious to people who do JS everyday, but to those of us occasional coders who want to get up and running quickly with the code this can be time consuming and frustrating.Other than that, it's pretty easy and fun to test the examples prior to jumping in the code and starting to play with them, adjust parameters, etc. These suggestions would enable alot of us to pick up stuff quickly by immersion.Great effort!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.