
Learning Three.js: The JavaScript 3D Library for WebGL - Second Edition
By :

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. 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 (like 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(); ... }
To see this effect in action, open the 06-screen-size-change.html
example and resize your browser window.
Change the font size
Change margin width
Change background colour