Center and Scale Loaded 3D Models in Three.js
When loading 3D models into a Three.js scene, they often arrive with unpredictable scales, off-center pivot points, or positions far from the scene’s origin. This article explains how to accurately calculate the physical dimensions of any loaded 3D model using bounding boxes, and how to programmatically center the model at the origin of your Three.js world.
1. Calculate the Model’s Bounding Box and Size
To find the exact physical dimensions of a loaded model (such as a
GLTF, OBJ, or FBX), you must compute its bounding box. Three.js provides
the THREE.Box3 utility, which calculates the minimum and
maximum coordinates of the geometry in 3D space.
import { Box3, Vector3 } from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
loader.load('path/to/model.gltf', (gltf) => {
const model = gltf.scene;
// 1. Compute the bounding box
const box = new Box3().setFromObject(model);
// 2. Calculate the size (width, height, depth)
const size = new Vector3();
box.getSize(size);
console.log(`Width: ${size.x}, Height: ${size.y}, Depth: ${size.z}`);
});Using Box3().setFromObject(object) is the most accurate
method because it traverses all child meshes within the group and
accounts for their world transformations.
2. Centrally Position the Model
Once you have the bounding box, you can find the geometric center of
the model. To place the model’s exact center at the scene coordinates
(0, 0, 0), you must subtract this center vector from the
model’s current position.
// 3. Calculate the geometric center
const center = new Vector3();
box.getCenter(center);
// 4. Center the model at the world origin (0, 0, 0)
model.position.x += (model.position.x - center.x);
model.position.y += (model.position.y - center.y);
model.position.z += (model.position.z - center.z);
// 5. Add the centered model to the scene
scene.add(model);By offsetting the model’s position by the negative values of its bounding box center, you override any offset pivot points baked into the original 3D file.
3. Scale the Model Uniformly (Optional)
If the loaded model is too large or too small for your scene, you can use the calculated size to scale it to a normalized fit.
For example, to scale the model so that its largest dimension is exactly 10 units:
const maxDimension = Math.max(size.x, size.y, size.z);
const targetSize = 10.0;
const scaleFactor = targetSize / maxDimension;
model.scale.set(scaleFactor, scaleFactor, scaleFactor);
// Re-calculate the box and center after scaling if you need to reposition it
box.setFromObject(model);
box.getCenter(center);
model.position.sub(center); Implementing these steps ensures that regardless of the software your 3D assets were exported from, they will consistently render at the correct size and position in your Three.js application.