Hello, I’m trying to load a .glb file (simple spherical shape) into a component of my React app, but I get a 404 in the console when its tried to load. Things i’ve tried:
a. Loaded another model successfully with a URL
b. Tried both glb and gltf formats
c. Put in public folder, put in src folder, tried with many filepaths “/sphere.glb” , “/sphere.glb”
d. Loaded the model into a webviewer to make sure it works
Ahh, thank you will look at those. They seem to both use web urls for the models, my problem is that I’m trying to use a local file so my app can work offline
Here is my code
import {useEffect} from ‘react’;
import * as THREE from “three”;
import { GLTFLoader } from ‘three/examples/jsm/loaders/GLTFLoader.js’;
export default function Page({ children } : { children: any }) {
useEffect(() => {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
50,
window.innerWidth / window.innerHeight,
1,
1000
);
camera.position.z = 96;
const canvas: any = document.getElementById('threeCanvas');
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
});
renderer.setSize(window.innerWidth / 3, window.innerHeight / 3);
document.body.appendChild(renderer.domElement);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
ambientLight.castShadow = true;
scene.add(ambientLight);
const loader = new GLTFLoader();
loader.load("/sphere.gltf", gltf => {
scene.add( gltf.scene );
}, undefined, function ( error ) {
console.error( error );
} );
const animate= () => {
renderer.render(scene, camera);
window.requestAnimationFrame(animate);
};
animate();
}, []);
Doh, of course. I ran out of space on codesandbox so I updated to use jsdeliver links now.
See my screen grab of the same glTFLoader example but loading a local file.
The monkey.glb is placed in my ./public/models/ folder.
And is referenced in the code using ./models/monkey.glb. This works.
Re: your code, sorry, I don’t know how to use React like the way you are showing it. If you are using React, then I would use React Three Fiber since it is full of good resources.
If I was doing it your way, i.e., mixing vanilla and React, then I wouldn’t use React.
I would do it this way. GLTF Model Loader. Press the <> for JavaScript source.
Maybe look more closely at your 404 error and see what path your browser is trying to download your sphere.gltf from.
so your browser is asking for ./images/sphere.glb
so put sphere.glb into wherever on your server, is the images folder that your webserver is apparently serving.
I don’t know what is wrong with your code, webserver or project setup.
In fact, I am unable to reproduce your error.
I won’t be updating my codesandbox examples to load models from the ./public/models/ folder.
But, if you want a working example of Three.js, in React, that runs locally and loads a locally hosted model,
then follow these commands exactly.