Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Mastering Threejs Camera: Types, Controls, and Real-World Examples

In Three.js, cameras define how we view the 3D scene. They’re like the eyes (or lens) through which we observe the virtual world. Explanation of how cameras are essential for rendering scenes in Three.js. The camera’s position and orientation affect the rendered scene.

Much like how a real-world camera lets you see the world from a specific perspective, a Three.js camera defines how users view your 3D scene. This article will cover the different types of cameras, how to implement basic camera controls, and practical, real-world examples for applying these cameras.

How Threejs Camera Work in 3D Space?

A camera in Three.js is defined by three important factors:

  • Position: The camera’s x, y, z coordinates in the 3D space.
  • Target: The point the camera is looking at in the scene.
  • View Frustum: This determines what the camera “sees” based on its field of view and other settings like aspect ratio and clipping planes.

Types of Threejs Cameras

There are two main types of cameras in Three.js The camera defines the viewer’s perspective in the 3D scene. The most common types are:

1. PerspectiveCamera

This is your go-to camera for most 3D scenes. It works just like our eyes or a regular camera – things far away look smaller, and parallel lines seem to meet in the distance. It’s perfect for creating realistic-looking 3D worlds.

The most common camera is the PerspectiveCamera, which mimics the way the human eye sees. Real-life example: Human eye or standard camera lens. This is how we naturally see the world. Objects appear smaller as they get farther away. This type of camera is ideal for most 3D applications, such as games and simulations, where a realistic depth perception is required 

const fov = 75; //It is an angle How wide you can see
const aspect = window.innerWidth / window.innerHeight;
const near = 0.1;
const far = 1000;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);

PerspectiveCamera argument include Field of view (in degrees), Aspect ratio, Near clipping plane, Far clipping plane.

Key characteristics:

  • Creates a sense of depth
  • Objects change size based on distance from the camera
  • Good for realistic, immersive scenes

Use cases:

  1. Most 3D applications aiming for realism
  2. Video games
  3. Architectural visualizations

2. Orthographic Camera

Now, this one’s a bit different. Imagine looking at a blueprint or a map. Everything stays the same size, no matter how far away it is. That’s what an orthographic camera does. It’s great for 2D games or technical drawings.

The OrthographicCamera provides an orthographic projection, meaning objects appear the same size regardless of their distance from the camera. This camera type is often used for 2D games, architectural visualizations, and UI elements in 3D scenes. It is particularly useful when precise measurements and proportions are needed.

const width = 10;
const height = width * (window.innerHeight / window.innerWidth);
const camera = new THREE.OrthographicCamera(
  width / -2, width / 2, 
  height / 2, height / -2, 
  0.1, 1000
);

Real-life example: Blueprint or architectural drawing. This is like looking at a technical drawing where parallel lines remain parallel, and objects maintain their size regardless of distance.

Key characteristics:

  • No perspective distortion
  • Objects remain the same size regardless of distance
  • Parallel lines stay parallel

Use cases:

  • 2D games (like old-school RPGs)
  • CAD applications
  • Isometric views in strategy games

3. CubeCamera

The CubeCamera captures a panoramic view of the scene from a specific position by rendering the scene six times, each time capturing the view along one of the cube’s faces. This camera type is commonly used for creating reflections or environment maps, which are essential for realistic rendering of reflective surfaces 

4. ArrayCamera

The ArrayCamera allows the creation of an array of cameras, enabling the switch between different perspectives or views. This can be useful for multi-camera setups or implementing camera transitions in complex scenes 

5. StereoCamera

The StereoCamera is used to create stereoscopic 3D effects by rendering separate views for the left and right eye, providing a sense of depth perception. This camera type is commonly used in virtual reality (VR) and augmented reality (AR) applications 

Key Characteristics of Threejs Cameras

All cameras in Three.js share some common characteristics, while specific types (like Perspective and Orthographic) have their own unique features. Let’s break these down:

  1. Position
    • Defines where the camera is located in the 3D scene. Is like we’ve got our camera, but where do we put it scene? In Three.js, you can place your camera anywhere in the 3D world. It’s like being a ghost cameraman you can float anywhere!
    • Set using camera.position.set(x, y, z) or individually with camera.position.x, etc.
    • camera.position.set(0, 5, 10);Real-world example: Imagine you’re filming a scene with an actor.
    • 0: The camera is centered horizontally with the actor.
    • 5: It’s elevated, maybe on a small crane, about 5 feet above the ground.
    • 10: It’s backed up 10 feet from the actor.
    • Play with these numbers like you’re moving your camera operator around the set!
  2. Rotation/Orientation
    • Determines which direction the camera is facing. This is all about where your camera is looking. In the real world, you might tell your camera operator, “Point the camera at that tree over there.”
    • camera.lookAt(0, 2, 0); Real-world example: You’re filming a nature documentary.
    • 0, 2, 0: You’re telling your camera operator to focus on a point about 2 meters high (maybe a bird’s nest in a tree).
    • Alternatively, you can rotate the camera directly: camera.rotation.set(0, Math.PI / 4, 0); This is like telling your operator, “Turn the camera 45 degrees to the right.”
  3. Field of View (FOV): How wide you can see?
    • Represents how much of the scene is visible. Remember how detectives in movies always say “Zoom and enhance!”? Well, in Three.js, you can actually do that! It’s called the Field of View (FOV):
    • camera.fov = 75; // Wide angle view camera.fov = 35; // Zoomed in view 35: You’re zooming in for a close-up of an actor’s face.
      camera.updateProjectionMatrix(); // Don’t forget this!
    • A higher number gives you a wider view, while a lower number zooms in. Just remember to call updateProjectionMatrix() after changing the FOV, or your camera won’t get the memo!
    • For PerspectiveCamera, it’s an angle. For OrthographicCamera, it’s defined by the frustum size.
  4. Near and Far Clipping Planes
    • This is like telling your crew where to place the “Action!” sign and the backdrop.
    • Define the range within which objects are rendered. It boundary of the camera view determing how close and far the object can be for the camera to see and rendered them. It improves the performance and controls what part of the scene is shown, its camera viewing range.
    • Near clipping planes is closest distance from the camera which object are visible and any object closes to the camera to this distance is will not be rendered.
    • Far clipping planes, is the farest distance from the camera which object is visible and any object beyound this distance is will not be rendered.
    • Objects too close (before near plane) or too far (beyond far plane) are not rendered.
    • Set during camera creation or with camera.near and camera.far.
  5. Aspect Ratio
    • This determines the shape of your camera’s view, just like choosing between filming in widescreen or standard format. The ratio of the camera’s width to its height of camera view.
    • Usually set to match the rendering canvas’s dimensions.
    • camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix();
  6. Viewport: Framing Your Shot
    • Defines where on the screen the camera’s view is rendered. This is like choosing which part of the camera’s view actually makes it into the final cut.
    • Can be set using setViewport() method.
  7. Zoom: Dolly In or Out
    • Instead of physically moving the camera, you’re adjusting the lens to make things appear closer or farther.
    • Allows zooming in or out without moving the camera.
    • Set using camera.zoom = value. camera.zoom = 2; // Objects appear twice as large camera.updateProjectionMatrix(); Real-world example: You want to make an object appear closer without moving the camera. It’s like using the zoom function on a video camera.

Perspective Camera Specific

  1. Focal Length
    • Influences the level of “perspective distortion”.
    • Controlled indirectly through the FOV. While not directly set in Three.js, it’s influenced by the FOV. A lower FOV is like a longer focal length.
    • Real-world example: Switching from a 24mm wide-angle lens (high FOV) to a 200mm telephoto lens (low FOV).
  2. Depth of Field
    • While not a built-in feature, can be simulated with post-processing effects.
    • This isn’t built into Three.js cameras but can be simulated with post-processing.
    • Real-world example: In portrait photography, when the subject is in sharp focus but the background is blurry.

Orthographic Camera Specific

Set during camera creation (left, right, top, bottom parameters).

Frustum Size: This defines the visible area in your scene, regardless of distance. Defines the visible area in world units.

const camera = new THREE.OrthographicCamera(-5, 5, 5, -5, 0.1, 1000);

Here’s a quick example demonstrating some of these characteristics:

// Create a perspective camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

// Set position
camera.position.set(0, 0, 10);

// Set rotation (looking at the origin)
camera.lookAt(0, 0, 0);

// Change FOV
camera.fov = 60;

// Change aspect ratio (e.g., after window resize)
camera.aspect = newWidth / newHeight;

// Set zoom
camera.zoom = 1.5;

// Update projection matrix after changes
camera.updateProjectionMatrix();

// Set viewport (render in the top-left quarter of the canvas)
renderer.setViewport(0, 0, window.innerWidth / 2, window.innerHeight / 2);

Camera Controls in Three.js

What if we want to move around? That’s where camera controls come in. It’s like giving your viewers the camera and letting them explore.

Orbit Controls: Circle Around

This is like giving your audience a camera on a string. They can swing around your scene, zoom in and out, and look up and down. Perfect for showcasing a 3D model or exploring a scene.

Orbit controls allow users to rotate, zoom, and pan around a target. It’s one of the most common ways of interacting with 3D scenes in Three.js.

const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableZoom = true;
controls.enablePan = true;

Real-world Example:

  • 3D product viewer: Think about viewing a 3D model of a car on a website where the user can rotate around it to see different angles.

Fly Controls: Freestyle Flying

Ever dreamed of being a drone pilot? Fly controls let you zoom around your 3D world in any direction. It’s great for open world experiences. Fly controls allow the camera to fly freely in any direction, without the constraints of gravity. This is often used in flight simulators or space exploration apps.

const controls = new THREE.FlyControls(camera, renderer.domElement);
controls.movementSpeed = 100;
controls.rollSpeed = Math.PI / 12;

Real-world Example: Flight simulators: Moving a camera in a 3D world, where users can “fly” in any direction.

FlyControls allow the camera to move freely in the scene using keyboard inputs (WASD, RF, QE, arrow keys). This control is useful for applications where the user needs to navigate through the scene from a first-person perspective.

PointerLock Controls: First-Person Adventure

This one’s for all you gamers out there. PointerLock controls are perfect for first-person experiences. It’s like strapping the camera to your character’s head.

const controls = new PointerLockControls(camera, document.body);

Remember, PointerLock controls only handle looking around. For a full first-person experience, you’ll need to add your own movement code. It’s like controlling your character’s body and head separately!

Putting It All Together: Lights, Camera, Action!

Let’s set up a simple scene with a camera and some controls:

Threejs camera

Example: Switching Between Camera Types

Here’s a simple example of how you might set up both cameras and switch between them:

Conclusion

Understanding the different types of cameras in Three.js, their real-world applications, and how to control them is essential for creating immersive 3D experiences. By mastering camera controls and basic concepts like positioning and animating the camera, developers can significantly enhance the interactivity and realism of their Three.js projects.

Related blog post on nextjs

  1. Comprehensive Guide to Integrating Three.js with Next.js
Mastering Threejs Camera: Types, Controls, and Real-World Examples

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top