Search code examples
3dthree.jsperspectivecamerafrustum

Making an object fit exactly inside the camera frustum in Three.Js


I am trying to make an object fit inside the camera frustum, and I went through all the trigonometry for that, and this is the code I used.

var setupCamera = function() {
    aspectRatio = window.innerWidth / window.innerHeight
    camera = new THREE.PerspectiveCamera( 45, aspectRatio, 1, 10000 );
    scene.add(camera);
}

var updateCamera = function() {
    var height = mesh1_BB.max.y;

    var width = mesh1_BB.max.x - mesh1_BB.min.x;
    var vertical_FOV = camera.fov * (Math.PI/ 180);

    var max_z = mesh1_BB.max.z;

    var horizontal_FOV = 2 * Math.atan (Math.tan (vertical_FOV/2) * aspectRatio);

    var distance_vertical = height / (2 * Math.tan(vertical_FOV/2));
    // alert ('vertical' + distance_vertical);
    var distance_horizontal = width / (2 * Math.tan(horizontal_FOV/2));
    // alert ('horizontal' + distance_horizontal);
    var z_distance = distance_vertical >= distance_horizontal? distance_vertical : distance_horizontal;

    camera.position.z = z_distance + max_z;
    camera.position.y = 0 ;
    camera.position.x = 0;
}

While I think the calculation for the camera distance is correct, this is the result I get: enter image description here

I thought the issue was changing the y position of the camera, and put it up with camera.position.y = height; but then this is what I get:

enter image description here

The result I want is the following (which is something I obtained by panning with the right-click button of the mouse and dragging it up until it fitted the whole canvas frame): enter image description here

I really hope you can help with this because this has been driving me crazy all day long ;-)

Thanks a lot!


Solution

  • I have not checked your distance calculations, but you looking straight down the z-axis, while the object isn't vertically centered around 0. Putting your camera.y at mesh1_BB.max.y / 2 should fix that.

    If you don't want to move your camera, at least point it towards the actual center of the object. In that case, using the (axis aligned) bounding box isn't 100% correct anymore.