Scale gltf model dynamically

Hello Guys, so basically im developing a web app and want to render 3d models in my react app. I am totally noob in 3d modelling and threejs so i don’t understand the technicality, but i managed to get things running so far. This is my code,

const Model = ({ model }) => {
    const gltf = useLoader(GLTFLoader, model);
    const [centeredPosition, setCenteredPosition] = useState()

    var box = new Box3().setFromObject(gltf.scene);
    var center = new Vector3();
    box.getCenter(center);

    useEffect(() => {
        setCenteredPosition(gltf.scene.position.sub(center))
        gltf.scene.rotation.y = Math.PI;
    })

    return (
        <>
            <primitive object={gltf.scene} scale={2} position={centeredPosition} />
        </>
    );
};


const RenderModel = ({ model }) => {
    return (
        <div className={styles["globe"]}>
            <Canvas>
                <color attach="background" args={["violet"]} />
                <directionalLight intensity={1} />
                <ambientLight intensity={1} />
                <spotLight position={[10, 15, 10]} angle={0.9} />
                <Suspense fallback={null}>
                    <Model model={model} />
                    <OrbitControls autoRotate />
                    {/* <Environment preset="sunset" background  /> */}
                </Suspense>
            </Canvas>
        </div>
    )
}

So basically, in my code you can see that i have set scale={2} statically and there are big and small models uploaded, i want to automatically scale them (zoom into them) according to their size upon rendering.

Help would be deeply appreciated.

drei has components for that, center, resize and bounds. also you should be using drei/useGLTF instead of useLoader(GLTFLoader because the latter wouldn’t be able to handle compression ootb. there’s just so much in drei that will help you, take a moment to scroll through it all GitHub - pmndrs/drei: 🥉 useful helpers for react-three-fiber

ps if you really just want a model centered

import { Center, Gltf } from '@react-three/drei'

<Canvas>
  <Center>
    <Gltf src={url} />
  </Center>
</Canvas>
  • useGltf is for when you need to make changes to the innards of the model scene, change props, colors, etc.

same with resize, it constrains a model to a fixed unit, all models will then have the same size

<Resize scale={2}>
  <Model />
</Resize>
1 Like

Thank you very much, everything is working now <3

So, i uploaded another model. The model is not vertically centered now, i believe it has somewhat to do with the model made.


Any idea how can i fix this?

skinned models return wrong bounds (as in box3.fromObject), you cant center them or rely on bounds. there’s some workaround somewhere but forgot where i’ve seen it.