2023-09-23

How to load a 3d model in .glb file format in ThreeJS?

I have read the official documentation but it seems too incomplete. The web browser display a black screen but not the model. In the browser console there isn't any error.

The following is the code:

import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const loader = new GLTFLoader();
loader.load('cube.glb', function(gltf) {
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.outputColorSpace = THREE.SRGBColorSpace;

    const scene = new THREE.Scene();
    scene.add(gltf.scene);

    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0, 0, 10);

    function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
    }

    document.body.appendChild(renderer.domElement);
    animate();
}, undefined, function(error) {
    console.error(error);
});

--- Edit September 22 ---

Now is showing the 3d model but all is black.

I editted the code in this way:

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

const loader = new GLTFLoader();

loader.load('cube.glb', function(gltf) {
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.outputColorSpace = THREE.SRGBColorSpace;

    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xffffff);
    scene.add(gltf.scene);

    scene.add(new THREE.AxesHelper(5));

    const light = new THREE.AmbientLight(0xff0000);
    scene.add(light);

    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000);
    camera.position.set(0, 0, 0.1);
    camera.lookAt(new THREE.Vector3());
    scene.add(camera);

    const controls = new OrbitControls(camera, renderer.domElement);
    controls.update();

    function animate() {
        requestAnimationFrame(animate);
        controls.update();
        renderer.render(scene, camera);
    }

    document.body.appendChild(renderer.domElement);

    animate();
}, undefined, function(error) {
    console.error(error);
});

You can see it from my own computer: http://pedrou2106.ddns.net:8080/

How to fix it?



No comments:

Post a Comment