How to Change Camera FOV in Three.js

Changing the field of view (FOV) of a perspective camera in Three.js is a straightforward process that involves modifying the camera’s fov property. This article provides a quick, step-by-step guide on how to update this value dynamically in your JavaScript code and ensure the 3D scene correctly projects the updated view.

To change the FOV of a THREE.PerspectiveCamera, you must update its fov property and then call the updateProjectionMatrix() method. Because Three.js caches the camera’s projection calculations for performance reasons, simply changing the property value will not visually update the scene until the matrix is manually updated.

Here is the standard code structure to achieve this:

// Assuming 'camera' is an instance of THREE.PerspectiveCamera

// 1. Assign a new FOV value (represented in degrees)
camera.fov = 45; 

// 2. Force Three.js to recalculate the camera projection
camera.updateProjectionMatrix();

Contextual Example: Implementing Zoom on Scroll

A common use case for changing the FOV is creating a zoom effect using the mouse wheel. Below is a practical example of how to implement this interaction:

window.addEventListener('wheel', (event) => {
    // Adjust FOV based on scroll direction
    if (event.deltaY < 0) {
        camera.fov -= 2; // Zoom in
    } else {
        camera.fov += 2; // Zoom out
    }

    // Define boundaries to prevent the FOV from flipping or distorting too much
    camera.fov = Math.max(10, Math.min(100, camera.fov));

    // Apply the changes
    camera.updateProjectionMatrix();
});

By keeping the change to the fov property followed immediately by camera.updateProjectionMatrix(), your Three.js application will smoothly transition to the new perspective without any rendering glitches.