Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Fit Camera to Object

Using three.js I have the following.

  • A scene containing several Object3D instances
  • Several predefined camera Vector3 positions
  • A dynamic width/height of the canvas if the screen resizes
  • A user can select an object (from above)
  • A user can select a camera position (from above)

Given an object being viewed and the camera position they have chosen how do I compute the final camera position to "best fit" the object on screen?

If the camera positions are used "as is" on some screens the objects bleed over the edge of my viewport whilst others they appear smaller. I believe it is possible to fit the object to the camera frustum but haven't been able to find anything suitable.

like image 616
fungus1487 Avatar asked Jan 30 '13 21:01

fungus1487


2 Answers

I am assuming you are using a perspective camera.

You can set the camera's position, field-of-view, or both.

The following calculation is exact for an object that is a cube, so think in terms of the object's bounding box, aligned to face the camera.

If the camera is centered and viewing the cube head-on, define

dist = distance from the camera to the _closest face_ of the cube 

and

height = height of the cube. 

If you set the camera field-of-view as follows

fov = 2 * Math.atan( height / ( 2 * dist ) ) * ( 180 / Math.PI ); // in degrees 

then the cube height will match the visible height.

At this point, you can back the camera up a bit, or increase the field-of-view a bit.

If the field-of-view is fixed, then use the above equation to solve for the distance.


EDIT: If you want the cube width to match the visible width, let aspect be the aspect ratio of the canvas ( canvas width divided by canvas height ), and set the camera field-of-view like so

fov = 2 * Math.atan( ( width / aspect ) / ( 2 * dist ) ) * ( 180 / Math.PI ); // in degrees 

three.js r.69

like image 176
WestLangley Avatar answered Sep 29 '22 04:09

WestLangley


Based on WestLangleys answer here is how you calculate the distance with a fixed camera field-of-view:

dist = height / 2 / Math.tan(Math.PI * fov / 360); 
like image 34
shi Avatar answered Sep 29 '22 04:09

shi