Loading...

Section

2.3 The Camera's Perspective: Looking at Your World

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

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:

  • 75 is the field of view in degrees.
  • window.innerWidth / window.innerHeight is the aspect ratio, dynamically set to match the browser window.
  • 0.1 is the near clipping plane.
  • 1000 is the far clipping plane.

Just like with other objects in our scene, we can position and rotate the camera using its position and rotation properties. For example, to move the camera back along the Z-axis, you would do:

camera.position.z = 5;

This places the camera 5 units away from the origin along the positive Z-axis. Understanding how to manipulate the camera's position and its FOV and aspect ratio will give you significant control over how your 3D world is perceived.

graph TD;
    A[Scene] --> B{Camera};
    B --> C[Renderer];
    C --> D[Screen];
    A -- Contains Objects --> B;
    B -- Defines Viewport --> C;
    C -- Projects to 2D --> D;