Skip to main content

Adding the camera

The camera is what "sees" your scene. What it sees is what gets rendered on your display. There are many types of cameras in three.js, and you can even have more than one in a scene and switch between them. For this tutorial, we will use a single PerspectiveCamera. This type of camera will cause objects to be rendered like they would appear in the real world: objects in the distance will appear smaller than objects that are closer.

Despite its short length, there are some important things happening in this function.

The first parameter that PerspectiveCamera takes is the vertical field of view measured in degrees. Typical human vision has a vertical range of 150 degrees with a 60 degree vertical range for central vision. This camera is set to 75 degrees which provides a reasonable default for most scenes.

The second parameter is the aspect ratio. You may have seen this written as a ratio such as 16:9, 21:9, or 4:3 in the context of televisions or computer displays. In short, it's the ratio of a display's width to its height. The camera needs this information to make sure that a square object appears square on your display. The function computes the ratio by dividing your browser window's width by its height.

The last two parameters specify the closest distance to and farthest distance from the camera, respectively, that an object in the scene can be and still be visible. Three.js uses Standard International (SI) units. So in this case, the camera can see things as close as 10 centimeters and as far away as 1,000 meters.

The function then sets the camera to look at the center, or origin, of the scene. Finally, it returns the newly created camera object.

function setUpCamera() {
const aspectRatio = window.innerWidth / window.innerHeight;
const camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 1000);
camera.lookAt(0, 0, 0);

return camera;
}