Zoom Extents in Three JS

Hi, I need to implement a functionality in my three.js application, where the objects gets fit to view when a function is called. I’m using both prespective and orthographic camera which can be changed. I attach my code I used . Somebody help we with this.

  const center = new THREE.Vector3();
  boundingBox.getCenter(center);

  const size = new THREE.Vector3();
  boundingBox.getSize(size);

  camera.position.copy(center);
  const maxDim = Math.max(size.x, size.y, size.z) / 2;

if (camera.type === 'PerspectiveCamera') {
    const fov = prespectiveCamera.fov * (Math.PI / 180);
    let cameraZ = Math.abs((maxDim / 4) * Math.tan(fov * 2));

    cameraZ *= 10; // add some extra space
    prespectiveCamera.position.z = cameraZ;

    const minZ = boundingBox.min.z;
    const cameraToFarEdge = minZ < 0 ? -minZ + cameraZ : cameraZ - minZ;

    camera.far = cameraToFarEdge * 3;
  } else if (camera.type === 'OrthographicCamera') {
    orthographicCamera.left = center.x - maxDim;
    orthographicCamera.right = center.x + maxDim;
    orthographicCamera.top = center.y + maxDim;
    orthographicCamera.bottom = center.y - maxDim;
    orthographicCamera.near = center.z - maxDim;
    orthographicCamera.far = center.z + maxDim;
  }


CameraControls should be able to help you out right away.

Is there a way can we achieve this without using external libraries?

Well, you could code / copy the functionality from external libraries by hand - the final code and the final effect will be the same :face_with_peeking_eye: (But if the question is - “does core three.js camera have a functionality like that” - then the answer is nope.)

oh ok. Thanks for the information :+1:. I’ll try.