Unable to bring in a three.js glTF model

Recently, I've been attempting to incorporate a 3D module into my three.js project. In my quest for answers, I delved into the documentation available here and here. However, no matter what I tried, all I saw was darkness. I even adjusted the Camera's z position to 5, but to no avail. This is just the beginning of my journey with Three.js. Interestingly, when I loaded the model on online Three.js viewers, it worked perfectly fine. Here's a snippet of my code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Import 3D Model into Three JS</title>

  <link rel="stylesheet" href="../common.css">
</head>
<body>
  <div id="container">

  </div>
</body>
  <script src="../three.js-master/build/three.js"></script>
  <script type="module">
    // import { THREE } from '../three.js-master/build/three.js';
    import { GLTFLoader } from '../three.js-master/examples/jsm/loaders/GLTFLoader.js';

    const container = document.querySelector('div#container');

    const path_to_model = './Mini-Game Variety Pack/Models/gltf/tree_forest.gltf.glb';
    const loader = new GLTFLoader();

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);

    loader.load(path_to_model, function (gltf)
    {
      console.log('Adding glTF model to scene...');
      scene.add(gltf.scene);
      console.log('Model added.');

      console.log('Moving camera 5z...');
      camera.position.z = 5;
      console.log('Camera moved.');
    }, undefined, function (error)
    {
      console.error(error);
    });

    container.appendChild(renderer.domElement);

    function animate()
    {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    }
    animate();
  </script>
</html>

I have organized my folders in the following manner:

  • Three JS/
    • common.css
    • three.js-master/
    • ImportModel/
      • index.html
      • Mini-Game Variety Pack/
        • Models/
          • gltf/
            • tree_forest.glb
            • tree_forest.gltf.glb

(Please note that not all files are displayed, only those deemed necessary)

The models were downloaded from here, specifically utilizing the tree_forest model. Upon loading the page, this is the bleak sight that greets me:

https://i.sstatic.net/Di37q.png

Currently, I am utilizing a Mac and running Five Server within VSCode.

Answer №1

<script src="../three.js-master/build/three.js"></script>
<script type="module">
    // import { THREE } from '../three.js-master/build/three.js';
    import { GLTFLoader } from '../three.js-master/examples/jsm/loaders/GLTFLoader.js';

Combining global scripts with ES6 modules can lead to unpredictable behavior. It is recommended to structure imports in an organized manner until the application functions correctly:

import * as THREE from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7a667c6b6b4e3e2fcf3f0ebf1f2ddfac0cee8">[email protected]</a>/build/three.module.js';
import { OrbitControls } from 'https://cdn.skypack.dev/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3773415d426c57514d41484404415c41">[email protected]</a>/examples/jsm/loaders/GLTFLoader.js';

It is also advisable to incorporate lighting into your scene to avoid a black screen. You can try adding lights using the following code snippets:

const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444 );
hemiLight.position.set( 0, 10, 0 );
scene.add( hemiLight );

const dirLight = new THREE.DirectionalLight( 0xffffff );
dirLight.position.set( 0, 0, 10 );
scene.add( dirLight );

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

I'm having trouble sending registration emails through my server. What could be causing this issue?

Currently, I am in the process of developing a registration system that automatically sends an email with the user's username and password once they have successfully registered. The registration process functions smoothly up until the point where the ...

Implementing JavaScript to provide personalized error messages for empty form fields

I am facing an issue with form validation on iPhone / Safari, as they do not recognize the required attribute. I want to display individual error messages below each empty input field using JavaScript. Although my code is functional, the problem is that t ...

Is there a way to prevent camera motion in three.js when the escape key and directional keys are activated?

While working on my project with Pointer Lock Controls, I came across a bug. When the player is pressing any directional keys on the keyboard and simultaneously presses the escape button to turn off the Pointer Lock Controls, the camera continues to move ...

Utilizing commas in JavaScript

Hi everyone, I'm having an issue with printing the message "Invalid password, Must Contain:". The problem I'm facing is that when I write the code in JavaScript, the comma is being interpreted as an operator instead of a regular English comma. Th ...

Connecting events to maps in AngularUI

Currently, I am working with AngularJS and the AngularJS UI modules to integrate Google Maps into my application and perform various actions on its events. One issue I have encountered is that the ui-events call function is not passing any parameters or da ...

CustomJS TextBox callback to adjust range of x-axis: Bokeh

I'm currently working on a web page that features a plot powered by an AjaxDataSource object. However, I am facing a challenge with implementing a TextInput widget that can modify the xrange of this plot. Here is a snippet of my code: source = AjaxDa ...

What steps can be taken to address issues with the csv to json conversion module?

I'm struggling to correctly match the title and genre in my module. There's a issue in the csv_json module where it doesn't handle properties properly, especially when the title includes "The". //csv file movieId,title,genre 1,"American P ...

How to retrieve element from templateUrl in AngularJS controller

I am facing a challenge in populating select(option) element inside a template html file from the controller. Although I have managed to do it successfully, I am unable to set a default value to avoid the initial empty option. Here is a snippet from the t ...

Express string declaration in a single TypeScript line

const restrictString = (str: string): string => str.match(/[ab]/g)?.join('') || '' Is there a way to restrict a string to only contain the characters 'a' and 'b' in a one-liner function? I am aware that this can ...

Utilizing Ionic to implement a conditional statement for comparing a string with information retrieved from an Observable source

I have a piece of code where I fetch data about a country as an observable. I then attempt to compare my string this.city with the this.capital that I got from the Observable. If they are not the same, I want to show a new paragraph in the HTML by changi ...

Making a RESTful API call using JavaScript

Can someone help me with making a call to a REST API using JavaScript, Ajax, or jQuery? curl -v -X PUT -H "Content-Type: application/json" -H "Accept: application/json" -X PUT --user user:password http://url -d "{\"name\": \"Marcus0.2\ ...

What is the best way to add a dynamic parameter to the URL?

Here is an example of my URL: https://my-website.com/api/players?countryId=1&clubId=2&playerName=abc The parameter values can vary. This is the code snippet I use: getDataPlayer(payload) { let params if(payload.countryId && payl ...

Searching for substrings in NodeJS using Express

In this code snippet, I am using Express JS and AES256 encryption to encode and decode simple text strings with a predefined key. The Express JS web server is set up to display specific elements based on the URL content. For instance, if the URL was abc. ...

Revamping the ejs template using an AJAX call

In my web app, users can search for recipes based on specific ingredients using the Edamam API. I implemented pagination to allow users to load more recipes when they click the "Load more" button, as Edamam only returns 20 recipes at a time. Here's ho ...

How to splice or add elements to an array using JavaScript function

Two buttons on my webpage are designed to add arrays to the orderArray. The arrays are then displayed as an HTML table, with each array having a corresponding button to remove it from the table. The removal process is working as intended, but after using . ...

What is the best way to execute a script on the homepage just one time?

I need some assistance with a script that should only run when a visitor arrives at my site for the first time. I want all content to be hidden initially and then revealed in a visually appealing way when the visitor clicks a button. However, I do not want ...

What is the best way to save the outcomes of several asynchronous $.get calls into an array?

I have a challenge where I need to retrieve data from an API for each item in an array, and then store that data in another array for further processing. However, I suspect the issue lies in the asynchronous nature of the requests, as the data may not be ...

Node server optimization for images

Currently, I have a server set up for uploading images. In order to enhance the image upload process, I am looking for ways to optimize it. This is my current function for uploading files: uploadImage(file, uid, res) { var fs = require('fs') ...

Is it crucial to invoke $ionicPlatform ready each time?

After noticing that $ionicPlatform.ready function is automatically executed in the app.js file generated by Ionic (within module.run), I pondered: Do I need to manually trigger $ionicPlatform.ready in controllers utilizing Cordova plugins which rely on on ...

Adjust the autofocus to activate once the select option has been chosen

Is there a way to automatically move the cursor after selecting an option from a form select? <select name="id" class="form-control"> <option>1</option> <option>2</option> <option>3</option&g ...