javascript – How to Embed a Sketchfab 3D Model in a React JSX Hero Section with Proper Sizing?
I’m trying to embed a Sketchfab 3D model in my React JSX hero section, but every time I do, the model appears extremely small—like a single pixel.
However, the model remains tiny. How can I properly size and scale the 3D model inside my hero section so it fits well and is fully visible?
sketchfab.com/3d-models/traveler-f86f5f2a779d496c95c9aca8ba13246f#comments
im trying to use that exact model directed by the link. Other models appear fine but not this.
Any help is appreciated!
import React, { Suspense, useRef, useEffect, useState } from "react";
import { Canvas, useFrame, useLoader, useThree } from "@react-three/fiber";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls, Environment, Html, useGLTF } from "@react-three/drei";
import { Box3, Vector3 } from "three";
import * as THREE from 'three';
// Model component that loads and animates the 3D model
function Model() {
const gltf = useLoader(GLTFLoader, "/traveler.glb");
const modelRef = useRef();
const mixer = useRef();
const { camera } = useThree();
useEffect(() => {
if (!gltf || !modelRef.current) return;
// Setup animation mixer
if (gltf.animations.length) {
mixer.current = new THREE.AnimationMixer(gltf.scene);
gltf.animations.forEach((clip) => {
mixer.current.clipAction(clip).play();
});
}
// Auto-scale and center model
const box = new THREE.Box3().setFromObject(modelRef.current);
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z);
const fov = camera.fov * (Math.PI / 180);
const distance = Math.abs(maxDim / Math.sin(fov / 2));
camera.position.set(center.x, center.y, distance * 1.5);
camera.lookAt(center);
const scaleFactor = 2 / maxDim;
modelRef.current.scale.setScalar(scaleFactor);
modelRef.current.position.set(-center.x, -center.y, -center.z);
}, [gltf]);
useFrame((_, delta) => {
if (mixer.current) mixer.current.update(delta);
});
return ;
}
// Loader component for displaying during model loading
function Loader() {
return (
);
}
// Main component
const HeroModel3D = () => {
return (
);
};
export default HeroModel3D;
Read more here: Source link