Now that we have a scene to hold our objects and a renderer to draw them, we need a way to see our 3D world. This is where the camera comes in. Think of the camera as your eye in the 3D scene. It defines what part of your scene is visible and how it's projected onto your 2D screen. Without a camera, you wouldn't be able to see anything!
Three.js offers several types of cameras, but for beginners, the most common and intuitive one is the PerspectiveCamera. This camera simulates how we see the real world, with objects that are farther away appearing smaller. It's defined by several key properties:
- Field of View (FOV): This determines how wide your camera's vision is. It's measured in degrees. A wider FOV means you can see more of the scene, but objects might appear distorted. A narrower FOV is like looking through binoculars, focusing on a smaller area.
- Aspect Ratio: This is the ratio of the canvas's width to its height (e.g.,
canvas.clientWidth / canvas.clientHeight). It's crucial for ensuring that your scene isn't stretched or squeezed when rendered on different screen sizes.
- Near Clipping Plane: This defines the closest distance at which objects will be rendered. Anything closer than this distance will be invisible.
- Far Clipping Plane: This defines the farthest distance at which objects will be rendered. Anything farther than this distance will be invisible. These clipping planes help to optimize rendering by not processing objects that are too close or too far away.
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );In this code snippet:
75is the field of view in degrees.window.innerWidth / window.innerHeightis the aspect ratio, dynamically set to match the browser window.0.1is the near clipping plane.1000is the far clipping plane.