Automatically resize the output when 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 like this:

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

Get Learning Three.js – the JavaScript 3D Library for WebGL - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.