Learn Three.js
eBook - ePub

Learn Three.js

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

Jos Dirksen

  1. 528 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Learn Three.js

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

Jos Dirksen

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Learn Three.js est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Learn Three.js par Jos Dirksen en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Open Source Programming. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
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...

Table des matiĂšres