Instructions for incorporating a glTF model into the environment:

I'm having trouble adding a 3D object to my scene.

An error occurred: Uncaught TypeError: Class constructor ol cannot be invoked without 'new' at new GLTFLoader

The main line causing the error is

let loader = new THREE.GLTFLoader();

I'm not sure what should go in the brackets, 'New'? .. or something else?

Constructor:

Model Size (2Mb): https://drive.google.com/file/d/1bPnC5coazNFIcsyvV9U29BFiFhXhriYg/view?usp=sharing

Source:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/master/examples/js/loaders/GLTFLoader.js"></script>

<script>

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 10; // Camera distance

    renderer = new THREE.WebGLRenderer();
    renderer.setClearColor(0x000000, 0);
    renderer.setSize(1280 , 720);

    renderer.domElement.setAttribute("id", "Church3DObj");
    document.body.insertBefore(renderer.domElement, document.body.firstChild);

    const aLight = new THREE.AmbientLight(0x404040, 1.2);
    scene.add(aLight);

    let loader = new THREE.GLTFLoader();
    let obj = null;

    loader.load('/3d/Church.gltf', function(gltf) {
        obj = gltf;
        obj.scene.scale.set(1.3, 1.3, 1.3);

        scene.add(obj.scene);

    });

</script>

</body>
</html>

Answer №1

The message is clear: you must use the 'new' keyword when invoking GLTFLoader, like this new GLTFLoader

By referring to the documentation provided in the code example, you can see that they initialize the loader with const loader = new GLTFLoader(); before using it.

Remember to create an instance of GLTFLoader.

Answer №2

To prevent encountering this issue, it is necessary to obtain the .js files from GitHub:

three.js, GLTFLoader.js, OrbitControls.js, three.module.js

<script src="scripts/three.js"></script> 
<script type="module"> src="scripts/GLTFLoader.js"></script> 
<script type="module"> src="scripts/OrbitControls.js"></script>// IF THERE IS A CAMERA CONTROL IN SPACE 

Place them in the project's root directory and open GLTFLoader.js. As of 05/24/2021 there are 64 lines found.

from './smthPath/smthPath/smthPath/three.module.js';

and eliminate the excess. (i.e., specify the path to the three.module.js file). In my case: from './three.module.js';

(If there is camera control, repeat the same process with the OrbitControls.js file on line 9)

from './three.module.js';

Moving forward, it is CRUCIAL in the script where everything comes together, to add type = "module", and import the files - resulting in

<script type="module">

import {GLTFLoader} from "./scripts/GLTFLoader.js";
import {OrbitControls} from './scripts/OrbitControls.js';

//...
</script>

CRITICAL

*For individuals new to 3D web development, but familiar with Cinema4D, 3Ds Max, ZBrush ... (like myself). You'll need not just a .gltf file but also a .bin file How can these be obtained?

  1. Visit the site [Scetchfab] ().
  2. Upload the model (configure for free download (can delete later)).
  3. Wait for processing. 4.download the required format (glFT)
  4. Delete the model from Scetchfab *

IMPORTANT

*** The final appearance of the html file ***

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dragon</title>

</head>
<body id="c" style="margin: 0;">

<!--3D-->
<script src="scripts/three.js"></script>
<script type="module" src="scripts/GLTFLoader.js"></script>
<script type="module" src="scripts/OrbitControls.js"></script>

<script type="module">
    import {GLTFLoader} from "./scripts/GLTFLoader.js";
    import {OrbitControls} from './scripts/OrbitControls.js';

    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x555555);

    const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 5, 15);

    const renderer = new THREE.WebGLRenderer({alpha: true, antialias: true});
    renderer.setClearColor(0x000000, 0);
    renderer.setSize(1920 , 1080);
    document.body.appendChild(renderer.domElement);



    const aLight = new THREE.AmbientLight(0x404040, 15);
    aLight.position.set(0,10,10)
    scene.add(aLight);

    const pLight = new THREE.PointLight(0xFFFFFF, 15);
    pLight.position.set(0,5,0)
    scene.add(pLight);

    const phelper = new THREE.PointLightHelper(pLight);
    scene.add(phelper);


    const loader = new GLTFLoader();
    let obj = null;




    loader.load("3d/Dragon/scene.gltf", function(gltf) {
        obj = gltf.scene;
        scene.add(gltf.scene);
    });


    const canvas = document.getElementById("c");
    const controls = new OrbitControls(camera, canvas);
    controls.target.set(0, 1, 0);
    controls.update();

    function animate(){
        requestAnimationFrame(animate)
        obj.rotation.y += 0.005;
        renderer.render(scene, camera)
    }
    animate();
</script>

</body>
</html>

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

Creating an object key using a passed literal argument in TypeScript

Can the following scenario be achieved? Given an argument, how can we identify the object key and access it? Any potential solutions? async function checkKey(arg:'key1'|'key2'){ // fetchResult returns an object with either {key1:&apo ...

The useEffect hook is not successfully fetching data from the local db.json file

I'm attempting to emulate a Plant API by utilizing a db.json file (with relative path: src\plant-api\db.json), and passing it from the parent component (ItemList) to its child (Item) but I am facing an issue where no data is being displayed ...

Setting the default time zone to UTC for Material UI date and time picker

Looking to implement a dialog in React with Material UI for users to input start and end date/time. The goal is to have the default start set to the beginning of the current day and the default end set to the end of the current day (UTC). However, I'm ...

Internet Explorer 10.0.9200 seems to have a tendency to overlook CSS styles

In my web application, I have implemented a 'tab toolbar' with 3 tabs. When a user clicks on a tab, the page displays different data based on which tab is selected. To visually indicate to the user which tab they have clicked on, I dynamically c ...

transfer the value of a method to a different component

In my Component called IncomeList, there is a method named sumValue. This method simply adds different numbers together to produce one value, for example 3+5 = 8. Similarly, in another Component named OutputList, the same logic is applied but with a method ...

Extracting Values from a jQuery Array Object

Good day everyone! Here is the code I am currently working with: var items = []; $(xml).find("Placemark").each(function () { var tmp_latLng = $(this).find("coordinates").text(); tmp_latLng = tmp_latLng.split(","); items.push({ name: ...

Encountered an issue retrieving tweets from the Twitter API 1.1

I recently completed an online tutorial from this site: However, I'm encountering an error message that simply says 'error: ' without any additional information. To start, here is my PHP script used to fetch the JSON output: <?php sess ...

Which kinds of data are ideal for storage within the Vuex (Flux) pattern?

Currently delving into the world of Vuex for the first time as I develop an application in Vue.js. The complexity of this project requires a singleton storage object that is shared across all components. While Vuex appears to be a suitable solution, I am s ...

Arrange the array of days and months in JavaScript

Attempting to rearrange a date Array from newest to oldest has proven challenging as the list.sort function only rearranges based on the initial number. The Array in question is as follows: var MyArray = ["13 Jun", "09 Jun", "25 Aug", "30 Jun", "13 Aug"]; ...

"splintering" HTTP requests

Currently, I am working on an Angular application that retrieves data from a REST server. Each piece of data we retrieve contains essential "core" information for basic representation, as well as additional "secondary" data like comments and other optional ...

Can we create a dynamic Context Menu?

I visited the following link: https://codepen.io/templarian/pen/VLKZLB After clicking on More Options, I need to display dynamically populated names like var Obj = [{name:"1st Item",taste:"sweet"},{name:"2nd item",taste:"spicy"}]; Instead of "Alert ...

Communication breakdown between components in Angular is causing data to not be successfully transmitted

I've been attempting to transfer data between components using the @Input method. Strangely, there are no errors in the console, but the component I'm trying to pass the data from content to header, which is the Header component, isn't displ ...

It seems like there is an issue with the res.render function as it is

My goal is to capture an input from my main website. Once the input is submitted, the page should automatically redirect to /view. Despite successfully triggering the redirection with console.log(), the res.render function does not seem to be working as ex ...

`Unveil the hidden edges of the Google timeline chart`

Does anyone know how to remove the chart border from a Google timeline chart using this script? <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load ...

Leveraging AJAX with React Router

Currently tackling a project utilizing React Router, encountering some challenges with data flow. Each page triggers an AJAX call to fetch data for the component. These calls have been placed within componentDidMount: // The following code is in ES6 comp ...

What is the best method for packaging a React component library?

Currently, I am working on developing a React component library that I aim to distribute via npm to reach a wide audience. In my development process, I utilize webpack and babel for packaging and code processing. However, as a newcomer to webpack, I am uns ...

Merge array and object destructuring techniques

What is the correct way to remove a value from an array? const ?? = { text: ['some text'] }; ...

Tips for dynamically inserting a tabbed element into a list using AngularJS

I am trying to dynamically add elements with tabs in the list, but I encounter a problem where the device info gets overridden from the last user. You can see the issue here: https://i.sstatic.net/O1uXK.jpg This is how my Tabs item looks like in HTML: & ...

Steer clear of directly modifying a prop in Vue.js to prevent errors

I have developed a custom DateField component. It is functioning properly but I am encountering an error message stating Avoid mutating the prop 'value'. This error occurs when I close the menu by clicking the Cancel button or by clicking outside ...

The correct assertion of types is not carried out during the initialization of generics through a constructor

I am encountering a minor issue with TypeScript, and I am uncertain whether it is due to a typo on my part or if TypeScript is unable to correctly infer the types. Let me provide all the necessary code to replicate the problem: interface IRawFoo { type: s ...