three.jstrigonometryperspectivecamera

How to adjust a three.js perspective camera's field of view to fit a sphere?


I have a sphere centered in front of my camera with a known radius and distance from the camera. How can I adjust the camera's field of view (FOV) to exactly fit the the camera to the sphere within an arbitrary viewport size?

Image of the angle I'm looking for

This answer is similar but I want to adjust the FOV instead of the camera's distance


Solution

  • To adjust the FOV to fit the sphere, I needed to use inverse trigonometric functions to calculate the angle from the triangle formed from the distance to the sphere and the furthest visible point on the sphere.

    Triangle that will give the correct angle: Image of the triangle that will give the correct angle

    // to get the fov to fit the sphere into the camera
    var vFOV = 2 * Math.asin(sphereRadius / distance);
    // get the project's aspect ratio to calculate a horizontal fov
    var aspect = this.width / this.height;
    // more trig to calculate a horizontal fov, used to fit a sphere horizontally
    var hFOV = 2 * Math.atan(Math.tan(vFOV / 2) / aspect);
    

    This will give the answer in radians. Multiply the hFOV or vFOV to degrees fov * (180 / Math.PI) and apply to camera.fov.

    I initially ran into the trap of using the wrong triangle. As this answer states "The sphere is being clipped for the same reason that if you stand close to a large sphere you can't see its "north pole"

    Don't do this; shown is the wrong triangle for a cropped view: image of the wrong triangle for a cropped view