Error loading GLTF file

I'm having trouble displaying a GLTF model using three.js. If someone could help me identify the issue in my code, I would greatly appreciate it.

        import {GLTFLoader} from "./GLTFLoader.js";

        var scene = new THREE.Scene();
        var camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth/window.innerHeight,
            .01,
            1000
        );
        var renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth,window.innerHeight);
        document.body.appendChild(renderer.domElement);

        var loader = new THREE.GLTFLoader();

        loader.load("scene.gltf",function(gltf){
            var obj;
            scene.add(gltf.scene);
        });
        var light = new THREE.HemisphereLight(0xFFFFFF, 0x000000, 2);
        scene.add(light);
        camera.position.set(0,0,100);
        function animate(){
            requestAnimationFrame(animate);
            renderer.render(scene,camera);
        }
        animate();

Answer №1

To begin, start by obtaining a free 3D model in glTF format from Sketchfab. Next, convert it to the glb format using this convenient website. After that, compress the file using the following command:

npx gltf-pipeline -i scene.glb -o model.glb --draco.compressionLevel=10

Then, utilize the command:

npx gltfjsx model.glb

This will generate a js file containing the model function. Simply copy the function and voila! Your task is complete. For a visual demonstration, feel free to check out this demo.

Answer №2

If you're encountering issues, start by inspecting your browser's console (often accessed by pressing ctrl+shift+i). If there are errors present, the file path may be incorrect. Try using console.log(gltf) to confirm if the object has loaded within your "onload" function. If it returns undefined, there could be an error in the code.

Another possibility is that your model is too large and may not be rendering properly (perhaps it is outside of your camera's render area), or the camera may be positioned inside the model with the object faces pointing outward (note that inward faces are sometimes culled by default in certain materials due to back-face culling).

To address this within your mesh, consider adding the following lines within your "onload" function:

gltf.scene.traverse(obj => {
  if (obj.type === "Mesh") {
    obj.doubleSided = true;
    // alternatively
    // obj.material.side = THREE.DoubleSide;
  }
})

This code snippet will analyze all objects in your gltf file, identify the meshes, and designate them as double-sided to ensure both inward and outward faces are rendered without back-face culling.

Additionally, try scaling down your object to a fraction of its original size, such as 0.1 or 0.01, to see if it becomes visible.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Searching for columns should be at the top of an angular datatable, not at the bottom

In my Angular 7 project, I am utilizing the library found at this link. I have followed the example provided, which can be seen here. Everything is working perfectly, except for the position of the search columns. I would like the search columns to appear ...

Angular Material (8) error code S2591: The variable 'require' is not defined in the current scope

Currently, I am attempting to record the date and time in the JavaScript console. Despite the code successfully logging the dates, an error message persists: Note: The code is functioning properly, with the dates being displayed in the console. It is only ...

Verify whether an email is already registered in firestore authentication during the signup process using Angular

When a user signs up for our app, I want them to receive immediate feedback on whether the email they are attempting to sign up with already exists. Currently, the user has to submit the form before being notified if the email is taken or not. This desire ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Angular animation triggered when a specific condition is satisfied

I am working on an animation within my Angular application @Component({ selector: 'app-portfolio', templateUrl: 'portfolio.page.html', styleUrls: ['portfolio.page.scss'], animations: [ trigger('slideInOut&apo ...

What is the best method for retrieving data through an ajax call in my modular JavaScript setup?

Working with a basic modular JavaScript structure, my goal is to request a random quote from an API and display it on an HTML page using Mustache.js. I previously achieved this without the modular approach, but now I'm attempting it in a more structur ...

Is it possible to duplicate a response before making changes to its contents?

Imagine we are developing a response interceptor for an Angular 4 application using the HttpClient: export class MyInterceptor implements HttpInterceptor { public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<an ...

Can a script be executed on a node.js module?

I have been developing a node package with an installation script that establishes a basic application structure. This script simply creates a few folders and generates an "admin" user if one does not already exist. Currently, the script performs multiple ...

Avoiding the need to wait for completion of the jQuery $.get function

Currently, I am executing a basic jQuery GET request as shown below and it is functioning correctly. $.get("http://test.example.com/do-something", function (data) { console.log("test work done"); }); The GET request is initiated without affecting the ...

CORS blocked the JavaScript Image's request

I am encountering an issue with my code that involves capturing selected divs using the HTML2Canvas library. However, when I try to download the captured image file, it is not working as expected. The error message I keep receiving is "Access to Image at ...

Refresh the data using the Ajax function

I am attempting to implement a delete function using Ajax. function delCatItem(catitem){ var theitem = catitem; $.ajax({ url: "movie/deleteitem/", type: "POST", data: { "movieid" : catitem ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

Synchronize CSS Properties with JavaScript Event

Is there a more efficient way to synchronize two properties using JavaScript or JQuery? For instance, when I have an editable text field and I switch it to an input box upon double click, how can I ensure that the input box adjusts its size along with the ...

What could be the reason for only one of my states being modified when I call my function?

Currently, I have a single state in React.js consisting of two key-value pairs for length validation and character validation: const [validation, setValidationState] = useState({ lengthValidation: "", characterValidation: "", }); These states are e ...

Unable to swap out string with text box in TypeScript

I am trying to swap __ with a text box in Angular 2/4. Take a look at the example provided in the link below. https://stackblitz.com/edit/angular-ajkvyq?file=app%2Fapp.component.ts ...

I am having trouble with Fullcalendar not loading my JSON data to display events

I've been experimenting with the fullcalendar JavaScript library, but I'm struggling to load data from my MySQL database onto the calendar. When I test my db-connect.php file, it does return the first entry in the table, yet the calendar remains ...

Flexible layout of perfectly square elements

I am currently working on creating a responsive grid layout consisting of squares that are positioned absolutely within their parent element. The goal is to ensure that when the page is resized, the squares scale proportionally with their parent container ...

Pass data to all routes in ExpressJS

After logging in, I am setting req.session variables as follows: req.session.loggedin = true req.session.firstname = loginDetails.firstName; I would like to streamline this process and pass this information to ALL routes without manually adding them to ea ...

Is there a way to detect a class change using jQuery?

Below is an example of a div: <div id="components-reconnect-modal" class="components-connecting-show"> <div id="1"> <div id="2"> <div id="3"> <div id="4"> </div> The ID will remain constant, but the class will ...

Vue.js routing and mixin dilemma

Calling all Vue developers! I am currently working on a vuebnb tutorial and running into an issue with routing and mixins. I have attempted to assign data before entering the router using the beforeRouteEnter guard, but it seems like my template is being r ...