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(); ... }