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;
}