An error stating 'THREE.OBJLoader is not a constructor' has occurred, along with an 'Unexpected token {' message in OBJLoader and OrbitControls

Attempting to showcase an OBJ 3D model as a wireframe that can be interactively moved using OrbitControls in Three.js. Being new to three.js, I apologize if I'm overlooking something obvious.

Successfully displayed a wireframe cube with OrbitControls. Also managed to display the OBJ 3D model as a wireframe independently. The issue arises when combining both methods.

Two approaches were tried:

  1. Inserting the OBJLoader into the cube environment (most promising).
  2. Adding OrbitControls to the wireframe OBJ environment (unsuccessful).

Experimented with different script orders like moving three.min.js, OrbitControls.js, OBJLoader.js, and model.js around, but to no avail.

Below is the code snippet:

<head>
   <style media="screen"> html, body { margin: 0; } #model_container { background-color: #333333; margin: 50px; } </style>
   <title>OBJ Wireframe</title>
   <script defer src="script/three/build/three.min.js"></script>
   <script defer src="script/three/examples/jsm/controls/OrbitControls.js"></script>
   <script defer src="script/three/examples/jsm/loaders/OBJLoader.js"></script>
   <script defer src="script/model.js"></script>
</head>
<body>
   <div id="model_container"></div>
</body>
const globalWidth = window.innerWidth - 100;
const globalHeight = window.innerHeight - 100;

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, globalWidth / globalHeight, 0.1, 1000);
camera.position.x = 300;
camera.position.y = -6;
camera.position.z = 1;

const renderer = new THREE.WebGLRenderer({
   antialias: true,
   alpha: true
});
renderer.setClearColor( 0xffffff, 0);
renderer.setSize(globalWidth, globalHeight);

const canvas = document.getElementById("model_container");
canvas.appendChild( renderer.domElement );

const ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);

const loader = new THREE.OBJLoader();
loader.load("assets/castle.obj", function(object) {
   const geometry = object.children[0].geometry;
   THREE.GeometryUtils.center(geometry);
   const material = new THREE.MeshLambertMaterial({});
   const mesh = new THREE.Mesh(geometry, material);
   mesh.material.wireframe = true;
   scene.add(mesh);
})

const controls = new THREE.OrbitControls(camera);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.rotateSpeed   = 0.1;
controls.target.set(0, 0, 0);

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

Struggling with these errors even after extensive research:

  • OrbitControls.js:9:
    Uncaught SyntaxError: Unexpected token {
  • OBJLoader.js:5:
    Uncaught SyntaxError: Unexpected token {
  • Uncaught TypeError: THREE.OBJLoader is not a constructor at model.js:23

Errors seem to originate from the THREE.js files themselves, making it challenging to resolve. Exhausted all resources and documentation available.

Hosting this on MAMP, but also tested on a server to rule out local file issues.

Answer №1

<script defer src="script/three/examples/jsm/controls/OrbitControls.js"></script>
<script defer src="script/three/examples/jsm/loaders/OBJLoader.js"></script>

It appears that the files are being loaded from the incorrect path. The files in the jsm directory are ES6 modules that should be imported using ES6 import syntax. To resolve this issue, try loading the files from the js directory instead:

<script defer src="script/three/examples/js/controls/OrbitControls.js"></script>
<script defer src="script/three/examples/js/loaders/OBJLoader.js"></script>

three.js R106

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

How can React useEffects avoid an infinite loop when using setData()?

const [resourceType, setResourceType] = useState("posts"); const [data, setData] = useState(""); useEffect(() => { console.log("use effects called: " + resourceType); fetch(`https://jsonplaceholder.typicode.com/${resourceType}`) .then((result ...

Challenges with form validation

Hello everyone, I'm a newbie to JS and struggling with my code. It seems like everything should work, but it just won't. The issue seems to be with the phone number form validation. I've written code that, in theory, should do the job, but ...

Having trouble maintaining the original events on a cloned element

My goal is to duplicate an element passed into a function and retain all associated events, including ones like $('.example').on('click', function(e) ... )} that are defined within the document ready. Here's what I'm trying: ...

Start by declaring a scope variable using AngularJS

My go-to method for retrieving data from the server and displaying it on various components like tables or charts is by using ng-init="controllerFunction()". This function needs to be called every time the page loads. While ng-init gets the job done, I ca ...

Step-by-step guide for creating a "load more on scroll" feature with Node.js and MongoDB

I currently have a Node server utilizing Express+Typescript to connect to a MongoDB database using Mongoose. Within the database, there is a collection named Products that the frontend (Angular 9) requests in order to display them. At the moment, the serv ...

Analyzing and inserting elements into an array of objects

The following code aims to: 1) iterate through the two arrays, 2) if an item exists in both arrays, add its value to the value of the matching item in the first array, 3) if the item is found in arr2 but not in arr1, add the item to arr1. The code funct ...

Import a fixed JSON document in Webpack

In the code I have, there is a construction that looks like this: var getMenu = function () { return window.fetch("portal/content/json/menu.json").then(function (data) { return data.json(); }); }; I attempted the following in my webpack.c ...

Can we expect React's useState to wait before executing subsequent logic, or will it immediately update the state and trigger a re-render

I have a specific scenario in my code where I am using the useState setter function in React to update a value on line 5. Everything seems to be functioning well without any errors, but I'm curious about something. Since setState updates the state and ...

Combining all code in Electron using Typescript

I am currently working on developing a web application using Electron written in Typescript and I am facing some challenges during the building process. Specifically, I am unsure of how to properly combine the commands tsc (used to convert my .ts file to ...

Tips for displaying an object's key/value pairs on a webpage

I'm attempting to use jQuery's .each() function to write the key/value pairs from an object onto the page. However, I am only able to get it to display the last key/value pair. If you want to check out a code example and demo, here is the link: ...

Some design elements are present in the interface. The functionality of the data tables is working properly, however, upon reloading the page, the table header shrinks. Interestingly

[![enter image description here][1]][1] This is the JavaScript code along with my footer and header references. The issue I am facing is with the design - initially, it shows a buggy design but when I click on the header, it displays the correct design. & ...

Learn how to clear the data in a Select multiple field while typing in another text field with reactjs

I have a current code snippet that I need help with. After selecting an option from the dropdown menu (CHIP), if the user starts typing in the text field, I want to clear the selection made in the CHIP. How can I achieve this functionality? const names = ...

Embedding the local host into a href link in NextJS

After creating a menu with the Link component in NextJs using href=#contact, I encountered an issue. When I use querySelector on this a element, the href unexpectedly changes to http://localhost:3000/#contact', preventing me from scrolling to that sec ...

Event response lacks necessary latlng data from Gmaps API

Currently, I am utilizing Angular UI Google Maps and facing an issue in retrieving the latlng when a map click event occurs. Although the map is responding, it is not providing the latlng information as expected. Below is the excerpt of my code: Controlle ...

Is there a way to ensure that an external file function completes before proceeding with the main code execution?

In my project, I have two key JavaScript files: main.js and load.js. Within load.js, there are two essential functions - getData, which makes an AJAX post call, and constHTML, which appends data based on the JSON array returned from the AJAX call. This app ...

Issues with React Native imports not functioning properly following recent upgrade

Hey there, I’ve been tasked with updating an old React-Native iOS project from version 0.25.1 to 0.48.0. However, I’m encountering several compiler issues and struggling to navigate through the code updates. The project includes an index.ios.js file s ...

Discovering a string within an array of objects using Angular JS

As a beginner in Angular JS with a limited background in JavaScript, I apologize if my explanation is not clear. I want to display an image based on a value in an array that contains objects. The following code works for me: <img ng-show="user.Groups[ ...

Troubleshooting Bootstrap: Navigation bar toggling causes JS functions to malfunction

My JS function is no longer working when the responsive website's breakpoint of 768px is activated (specifically, the nav var toggle/collapse). This is causing the problem where the JS function stops working. The HTML code in question is: <div cl ...

In general, I am seeking ways to streamline my code that is excessively repetitive. More specifically, I am attempting to utilize a single function to access multiple states

Looking for assistance with my new project related to enhancing my skills in react/javascript. I am creating a dice rolling application specifically for tabletop gaming. The aim is to allow users to roll any number of dice of the same size, as well as mult ...

What is the best way to eliminate a blank array in JavaScript?

After countless hours of searching, I am reaching out for help with an issue that has me stumped. My Node.js application relies on JSON files for project configurations. Using the 'fs' module, I read the JSON file, parse it into a JavaScript obje ...