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

Arrow left icon
Profile Icon Jos Dirksen
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (8 Ratings)
Paperback Jan 2015 300 pages 1st Edition
eBook
S$12.99 S$59.99
Paperback
S$74.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jos Dirksen
Arrow right icon
Free Trial
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (8 Ratings)
Paperback Jan 2015 300 pages 1st Edition
eBook
S$12.99 S$59.99
Paperback
S$74.99
Subscription
Free Trial
eBook
S$12.99 S$59.99
Paperback
S$74.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781783981182
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jan 30, 2015
Length: 300 pages
Edition : 1st
Language : English
ISBN-13 : 9781783981182
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 S$6 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 S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 194.97
Game Development with Three.js
S$44.99
Learning Three.js: The JavaScript 3D Library for WebGL - Second Edition
S$74.99
Three.js Cookbook
S$74.99
Total S$ 194.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.