Learn Three.js
eBook - ePub

Learn Three.js

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

Jos Dirksen

Condividi libro
  1. 528 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Learn Three.js

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

Jos Dirksen

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Learn Three.js è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Learn Three.js di Jos Dirksen in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Open Source Programming. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788835978

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...

Indice dei contenuti