Calculate camera fov so that the camera view fits the object dimensions

Hi all,

Is there a way to calculate the camera’s fov so that the camera view fits the size of the object?

This is my PG: Babylon.js Playground

I made a sample code where I created a box and then I positioned the camera very close to the box, after that I set the camera’s fov value (set manually) so that all parts of the object can be seen. but I want the camera’s fov value to adjust based on the size of the box, until the box looks ideal (not too close and not too far)

Babylon camera fov is vertical value (by default), so with Pythagore, you can compute the triangle that will fit the view.
distance from camera position to the object on 1 side, vertical viewed length on the other.
Once you have the hypothenus, you can compute the cosine of the angle from the camera. then an acos to get half angle.
Add some margin and you should be good.

Calculate Dynamic | Babylon.js Playground (babylonjs.com)

Beware, when adding rotation, the vertSize is the projected world height. Use some bouding box for example.

7 Likes

That would also work: var halfAngle = Math.atan(vertSize / distance);

2 Likes

cool, it’s work. Thanks @Cedric

1 Like

In my use case it was rather hard to calculate the distance, but I had 4 points (vectors) in the YZ-plane

  • max: the maximum height I would like to see
  • min: the minimum height I would like to see
  • C: the camera position
  • O: a common origin

So I could determine the angles (in 2d) between max-C-O and min-C-O, take the max of both angles, multiply by 2, and use that as Field Of View of the camera.

1 Like