I am trying to achieve a "Zoom Extents"-like function in three.js. After I start this function the camera should zoom so that all objects in the scene are visible on the screen. The code I have so far is this:
function fitAll(bbox)
{
// create an helper
helper = bbox;
// get the bounding sphere
var boundingSphere = helper.box.getBoundingSphere();
// calculate the distance from the center of the sphere
// and subtract the radius to get the real distance.
var center = boundingSphere.center;
var radius = boundingSphere.radius;
var distance = center.distanceTo(camera.position);
var realHeight = Math.abs(helper.box.max.y - helper.box.min.y);
var fov = 2 * Math.atan( ( realHeight / (window.innerWidth / window.innerHeight) ) / ( 2 * distance )) * ( 180 / Math.PI );
camera.fov = fov;
camera.updateProjectionMatrix();
}
Where bbox is a object which has a bounding box (in this example I use a bounding box defined by all objects in the scene).
When I use the function, the camera looks at the midpoint of the bounding box and adjusts the fov a little bit. Afterwards only a part of the bounding box is visible on the screen. It seems that the distance between the midpoint of the bounding box and the camera mid point is not correct. My question therefore is: How can I position the camera in the right distance to the bounding box, so that everything is on the screen?
Also see my jsfiddle: https://jsfiddle.net/MS_DOS_86/ytfk6heg/1/
Looking forward for an answer!