Using Three.js to load .gltf files

As I delve into learning three.js, I've encountered an issue with a basic script intended to load an external 3D model. Despite not receiving any console errors and confirming that the model is fully loaded, it remains invisible in the browser. I'm seeking assistance in identifying what might be causing this problem and how to resolve it. It's puzzling why it's currently not functioning as expected.

<html lang="en">
<head>
    <title>External Asset</title>
    <meta charset=utf-8>
    <link rel="stylesheet" type="text/css" href="canvas.css">
</head> 
<body>
    <script src="../three.js-master/build/three.min.js"></script>
    <script src="../three.js-master/examples/js/loaders/GLTFLoader.js"></script>
    <!-- <script src="../three.js-master/examples/js/controls/OrbitControls.js"></script> -->
    <script>
        var camera, scene, renderer;
        //var controls;
        var loader;

        init();

        function init() {
            //Renderer
            renderer = new THREE.WebGLRenderer( {antialias: true} );
            var width = window.innerWidth;
            var height = window.innerHeight;
            renderer.setSize( width, height );
            renderer.setClearColor ( new THREE.Color( "rgb( 198,215,244 )" ), .5 );
            document.body.appendChild( renderer.domElement );

            scene = new THREE.Scene();

            //Light Source
            var light = new THREE.PointLight( new THREE.Color( "rgb( 232,227,92 )" ), 3, 100 );
            light.position.set( 5,5,0 );
            scene.add( light );

            //Create Camera
            camera = new THREE.PerspectiveCamera (45, width/height, 1, 1000);
            camera.position.set( 5,5,5 );
            camera.lookAt( 0, 0, 0 );

            //Load asset
            loader = new THREE.GLTFLoader();
            loader.load( '../models/gltf/scifi-girl/scene.gltf',  
                function( gltf ) {
                    scene.add( gltf.scene );
                }, 
                function ( xhr ) {
                    console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
                },
                function ( error ) {
                    console.log( 'An Error Occurred' );
                }
            );

            renderer.render( scene, camera );
        }
    </script>
</body>

Answer №1

To improve your code, consider implementing a render loop. Currently, you're only rendering once, and your .gltf file loads asynchronously after that initial render.

Referencing the Creating a scene documentation:

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

This method ensures that calling animate() will initiate a continuous loop, rendering your scene at 60 frames per second. As your .gltf file finishes loading, it will seamlessly integrate into the scene and be automatically rendered in the subsequent frame.

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

Moving the grid in threejs when the camera approaches its edge: A guide

Is there a way to create an infinite grid plane without having to generate a massive grid each time? I attempted adjusting camera.position.z and grid.position.z, but the grid's z position remains at 0 when moving the camera. Looking for functionalit ...

What is the best way to shift a three.js model to the right side of the screen?

Recently, I've delved into learning three.js and I'm curious to know if it's possible to shift a 3D model to the right side of the screen instead of having it centered. To better illustrate my query, I've included an image below: http ...

Include the referrer header when using the chrome.downloads API

I have been working on developing an extension that replicates the Ctrl+Click to save image functionality from Opera 12. In my extension, I am utilizing chrome.downloads.download() in the background script to trigger downloads, while a content script is re ...

Steps for invoking a method on page refresh across all pages with vue.js

It is essential for the following function to run on every page refresh, regardless of the current route. For example: this.executeonEverypage() ...

What steps can be taken to fix the issue of 'this is not defined' when trying to extend EventEmitter?

The code snippet below is encountering an error: var EventEmitter = require('events'); class Foo extends EventEmitter{ constructor(){ this.name = 'foo'; } print(){ this.name = 'hello'; co ...

Sending a function from the useReducer state to the component requiring it

I am relatively new to React's useReducer and I am attempting to create a reducer with a handleChange function for state updates. My goal is to pass this handler down to a child component (specifically, react-select components) so that I can modify th ...

Executing a function inside of JavaScript code

I'm attempting to utilize a function within the "initialize" function of GoogleMaps. Here's what I have: <script> function initialize(){ // initialization parameters function drop(){ //code to drop a marker } } google.maps ...

Looking for assistance with transferring a data attribute to a form redirection

I'm seeking assistance with a coding dilemma I've encountered. To provide some background, I have a list of items on my website, each featuring a 'Book Now' button that redirects users to different pages. Recently, I incorporated a mod ...

Query the number of Firebase instances using the firebase.appCount property in Firebase v

When setting up Firebase in my React applications, I typically initialize it as follows: if (firebase.apps.length < 1) { firebase.initializeApp(firebaseConfig); // Additional initialization for other Firebase products } This method was working flaw ...

Resolving JavaScript ES6 module names

Forgive me if this is a silly question, but I am having trouble understanding how this particular line of code functions: import React from 'react'; My confusion lies in who and where exactly searches for the name 'react'? For instanc ...

The conversation refusing to end

When attempting to add an entry to a database using a popup window, I encountered errors in the console upon clicking in the Name field. The error message displayed was: VM247 1:1 Uncaught TypeError: Cannot set property 'result' of undefined If ...

Create a pop-up window within a single controller using Angular.js

I followed a tutorial to create this code. I am interested in learning how to utilize just one controller for generating the dialog box. Currently, I am using two controllers for this project. Any guidance or tips would be greatly appreciated. View my cod ...

Tips for showing a portion of a string and adding ellipses if it exceeds a certain length

I'm currently using the .map function to display descriptions. I want only 35 characters to be shown, followed by "..." if it exceeds that length. For example: This is a description of thirty five ... This is what I'm trying to achieve: <div ...

What is the best way to display a Facebook-like pop-up on a website

I am looking to implement a Facebook like box pop-up on my website for visitors. While I know how to show the pop-up, I am trying to determine how I can detect if someone has already liked my page in order to prevent the Facebook pop-up from appearing agai ...

Track the status of an extensive MySQL query using PHP

Looking for a way to show the progress percentage of a lengthy mysql query using php? Well, you can create a filter button in your database that triggers a javascript function through ajax and calls a php file. function show(){ $.ajax({ ...

Separating divs with a white line to cater to various mobile display sizes

I've put together a simplified version where I removed all styling except for the background color and height for easy visibility. Can anyone shed light on why there is a white line appearing between the divs? It seems to be appearing randomly dependi ...

Display a photo transitioning from black and white to color in a loading fashion, moving from left to right

Is there a way to enhance the clarity of the question's title? I have an interesting effect where text starts off in grey color and then transitions to black using keyframes in CSS with the animate property. I'm curious about how I can achieve ...

When employing useNavigation, the URL is updated but the component does not render or appear on the

Check out this code snippet: https://codesandbox.io/p/sandbox/hardcore-lake-mptzw3 App.jsx: import ContextProvider from "./provider/contextProvider"; import Routes from "./routes"; function App() { console.log("Inside App" ...

Activate single elements one at a time

If you want to understand the question better, take a look at my code on jsfiddle. Each Div contains only one link. When you click on the link, it sets the Div to active and shows a hidden Div within it. Clicking the link again toggles the active style an ...

Is there a method to consistently implement a controller function across all routes within a router file in Express?

I have the following code snippets within an application. I am looking for a way to apply "authController.isLoggedIn" to each instance of "router.get" without having to repeat it multiple times. Initially, I thought using router.use might be the solution ...