Camera guide
Three.js Fit Camera to Object
Use Box3 to measure the object, then place the PerspectiveCamera far enough away for the largest dimension to fit inside the view.
Fit camera helper
function fitCameraToObject(camera, object, controls, offset = 1.25) {
const box = new THREE.Box3().setFromObject(object);
const size = box.getSize(new THREE.Vector3());
const center = box.getCenter(new THREE.Vector3());
const maxSize = Math.max(size.x, size.y, size.z);
const fitHeightDistance = maxSize / (2 * Math.atan((Math.PI * camera.fov) / 360));
const fitWidthDistance = fitHeightDistance / camera.aspect;
const distance = offset * Math.max(fitHeightDistance, fitWidthDistance);
const direction = new THREE.Vector3(0, 0.25, 1).normalize();
camera.position.copy(center).add(direction.multiplyScalar(distance));
camera.near = Math.max(distance / 100, 0.01);
camera.far = distance * 100;
camera.updateProjectionMatrix();
camera.lookAt(center);
if (controls) {
controls.target.copy(center);
controls.update();
}
return { center, size, distance };
}
What the helper does
Measures bounds
Box3.setFromObject reads the world-space bounds of a mesh, group, or loaded GLB scene.
Finds the largest size
The largest dimension gives a conservative distance that works for tall, wide, and deep objects.
Sets clipping planes
Near and far planes are updated after the distance is known, which prevents clipping on oversized models.
Updates controls
OrbitControls should target the same center point that the camera looks at.
Common fit camera problems
- If the object is invisible, check scale first with the GLB viewer.
- If the object is cut off, increase the offset from 1.25 to 1.5.
- If the camera points at empty space, update lookAt after changing camera position.
- If OrbitControls snaps back, update controls.target and call controls.update.
FAQ
Does this work with GLTFLoader?
Yes. Pass gltf.scene into the helper after the file has loaded and been added to the scene.
Should I fit by width or height?
Use both. The helper checks aspect ratio and uses the larger required distance, so wide canvases and tall canvases both work.
Why does my model still look tiny?
The model may contain hidden or far-away child objects that enlarge the Box3 bounds. Inspect the model hierarchy and remove stray nodes if needed.