Learn Three.js
eBook - ePub

Learn Three.js

Programming 3D animations and visualizations for the web with HTML5 and WebGL, 3rd Edition

Jos Dirksen

Share book
  1. 528 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Learn Three.js

Programming 3D animations and visualizations for the web with HTML5 and WebGL, 3rd Edition

Jos Dirksen

Book details
Book preview
Table of contents
Citations

About This Book

Create and animate stunning 3D browser based graphics with Three.js JavaScript library

Key Features

  • Enhance your 3D graphics with light sources, shadows, advanced materials, and textures
  • Load models from external sources, and visualize and animate them directly from JavaScript
  • Create your own custom WebGL shader and explore the postprocessing feature of Three.js

Book Description

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.

What you will learn

  • Work with the different types of materials in Three.js and see how they interact with your 3D objects and the rest of the environment
  • Implement the different camera controls provided by Three.js to effortlessly navigate around your 3D scene
  • Work with vertices directly to create snow, rain, and galaxy-like effects
  • Import and animate models from external formats, such as OBJ, STL, and COLLADA
  • Create and run animations using morph targets and bones animations
  • Explore advanced textures on materials to create realistic looking 3D objects by using bump maps, normal maps, specular maps, and light maps
  • Interact directly with WebGL by creating custom vertex and fragment shaders

Who this book is for

The ideal target audience for this book would be JavaScript developers who who want to learn how to use the Three.js library

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Learn Three.js an online PDF/ePUB?
Yes, you can access Learn Three.js by Jos Dirksen in PDF and/or ePUB format, as well as other popular books in Computer Science & Open Source Programming. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788835978
Edition
3

Animations and Moving the Camera

In the previous chapters, we have seen some simple animations, but nothing too complex. In Chapter 1, Creating Your First 3D Scene with Three.js, we introduced the basic rendering loop, and in the chapters following that, we used that to rotate some simple objects and show a couple of other basic animation concepts. In this chapter, we're going to look in more detail at how animation is supported by Three.js. We will look in detail at the following four subjects:
  • Basic animation
  • Moving the camera
  • Morphing and skinning
  • Loading external animations
We start with the basic concepts behind animations.

Basic animations

Before we look at the examples, let's do a quick recap of what was shown in Chapter 1, Creating Your First 3D Scene with Three.js on the render loop. To support animations, we need to tell Three.js to render the scene every so often. For this, we use the standard HTML5 requestAnimationFrame functionality, as follows:
render(); function render() { // render the scene renderer.render(scene, camera); // schedule the next rendering using requestAnimationFrame requestAnimationFrame(render); } 
With this code, we only need to call the render() function once when we're done initializing the scene. In the render() function itself, we use requestAnimationFrame to schedule the next rendering. This way, the browser will make sure the render() function is called at the correct interval (usually around 60 times a second). Before requestAnimationFrame was added to browsers, setInterval(function, interval) or setTimeout(function, interval) were used. These would call the specified function once every set interval. The problem with this approach is that it doesn't take into account what else is going on. Even if your animation isn't shown or is in a hidden tab, it is still called and is still using resources. Another issue is that these functions update the screen whenever they are called, not when it is the best time for the browser, which would result in higher CPU usage. With requestAnimationFrame, we don't tell the browser when it needs to update the screen; we ask the browser to run the supplied function when it's most opportune. Usually, this results in a frame rate of about 60 fps. With requestAnimationFrame, your animations will run more smoothly and will be more CPU- and GPU-friendly, and you don't have to worry about timing issues yourself.

Simple animations

With this approach, we can very easily animate objects by changing their rotation, scale, position, material, vertices, faces, and anything else you can imagine. In the next render loop, Three.js will render the changed properties. A very simple example, based on the one we already saw in Chapter 1, Creating Your First 3D Scene with Three.js, is available in 01-basic-animation.html. The following screenshot shows this example:
60 FPS (35-60)
The render loop for this is very simple. Just change the properties of the involved meshes, and Three.js handles the rest. Here's how we do this:
function render() { cube.rotation.x += controls.rotationSpeed; cube.rotation.y += controls.rotationSpeed; cube.rotation.z += controls.rotationSpeed; step += controls.bouncingSpeed; sphere.position.x = 20 + ( 10 * (Math.cos(step))); sphere.position.y = 2 + ( 10 * Math.abs(Math.sin(step))); scalingStep += controls.scalingSpeed; var scaleX = Math.abs(Math.sin(scalingStep / 4)); var scaleY = Math.abs(Math.cos(scalingStep / 5)); var scaleZ = Math.abs(Math.sin(scalingStep / 7)); cylinder.scale.set(scaleX, scaleY, scaleZ); renderer.render(scene, camera); requestAnimationFrame(render); } 
Nothing spectacular here, but it nicely shows the concept behind the basic animations we discuss in this book. In the next section, we'll take a quick sidestep. Besides animations, an important aspect, which you'll quickly run into when working with Three.js in more complex scenes, is the ability to select objects on screen using the mouse.

Selecting objects

Even though not directly related to animations, since we'll be looking into cameras and animations in this chapter, it is a nice addition to the subjects explained in this chapter. What we'll show here is how you can select an object from a scene using the mouse. We'll first look at the code required for this before we look at the example:
var projector = new THREE.Projector(); function onDocumentMouseDown(event) {

var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5);
vector = vector.unproject(camera);

var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
var intersects = raycaster.intersectObjects([sphere, cylinder, cube]);

if (intersects.length > 0) {
console.log(intersects[0]);
intersects[0].object.material.transparent = true;
intersects[0].object.material.opacity = 0.1;
}
}
In this code, we use THREE.Projector together with THREE.Raycaster to determine whether we've clicked on a specific object. What happens when we click on the screen is the following:
  1. First, THREE.Vector3 is created based on the position where we've clicked on the screen.
  2. Next, with the vector.unproject function, we convert the clicked position on screen to coordinates in our Three.js scene. In other words, we unproject from scree...

Table of contents