Book Image

Learn Three.js - Third Edition

By : Jos Dirksen
1 (1)
Book Image

Learn Three.js - Third Edition

1 (1)
By: Jos Dirksen

Overview of this book

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.
Table of Contents (14 chapters)

Automatically resize the output when the browser size changes

Changing the camera when the browser is resized can be done pretty simply. The first thing we need to do is register an event listener as follows:

window.addEventListener('resize', onResize, false); 

Now, whenever the browser window is resized, the onResize function, which we'll specify next, is called. In this onResize function, we need to update the camera and renderer, as follows:

function onResize() { 
  camera.aspect = window.innerWidth / window.innerHeight; 
  camera.updateProjectionMatrix(); 
  renderer.setSize(window.innerWidth, window.innerHeight); 
} 

For the camera, we need to update the aspect property, which holds the aspect ratio of the screen, and for the renderer, we need to change its size. The final step is to move the variable definitions for camera, renderer, and scene outside of the init() function so that we can access them from different functions (such as the onResize function), as follows:

var camera; 
var scene; 
var renderer; 
 
function init() { 
  ... 
  scene = new THREE.Scene(); 
  camera = new THREE.PerspectiveCamera(45, window.innerWidth / 
window.innerHeight, 0.1, 1000); renderer = new THREE.WebGLRenderer(); ... }