How can I transfer the value of a local variable to a function variable in Three.js JSON Loader?

I am attempting to import an external JSON model into the scene and assign its value to a variable called head, and then add it to the scene.

This is what I have done:

    var loader = new THREE.JSONLoader();

    this.head = loader.load( "eagle2.js", function( geometry ) {

        var material = new THREE.MeshPhongMaterial(), head;
        head = new THREE.Mesh( geometry, material );
        head.scale.set( 200, 200, 200 );
        head.position.y = 0;

        return head;
    } );

    this.mesh.add(this.head);

My goal is to load the JSON model and assign all the meshes to the head variable within the current function. However, when I execute the code above, it shows a type error in the console. The model loads successfully, but the error message is:

TypeError: a is undefined Three.js Line 55

How can I fix this error?

Answer №1

When using the load method of JSONLoader, it does not return anything directly. Instead, it initiates an asynchronous call to the server and triggers a callback function to handle the returned data. To properly use this method, follow this example:

let self = this;
let loader = new THREE.JSONLoader();

loader.load( "eagle2.js", function( geometry ) {

    let material = new THREE.MeshPhongMaterial(), head;
    head = new THREE.Mesh( geometry, material );
    head.scale.set( 200, 200, 200 );
    head.position.y = 0;

    self.head = head;
    self.mesh.add(head);
} );

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

Is it possible in MVC to send JSON data to the view in the format of a two-dimensional array?

My goal is to receive JSON data in the following format within the view: [{"name":"NewWork", "data":[{"\/Date(1398787200000)\/",196}, {"\/Date(1398009600000)\/",62}, {"\/Date(1397836800000)\/",65}] ...

`ACCESS DENIED: Unauthorized access attempt detected in Node.js``

When attempting to connect, MySQL is establishing a connection with an unfamiliar IP address. Refer to the code below: .env MYSQL_HOST=domain.example.com MYSQL_USER=**** MYSQL_PASSWORD=**** MYSQL_DB=**** MYSQL_PORT=3306 connection.js const mysql = requir ...

Having trouble generating package.json with npm init on my Mac

Every time I attempt to generate a package.json file by using the command npm init, I encounter the following issue: npm http GET https://registry.npmjs.org/init npm http 304 https://registry.npmjs.org/init npm http GET https://registry.npmjs.org/daemon n ...

Sleek descending motion effect

I have created a simple function, but it is not animating smoothly and seems to lag... I am using it for a div sized at 1600x700 pixels on page load $(document).ready(function(){ $('#slider').slideDown(500); }); Is there any way to ensure s ...

Mapping and merging with JQ

When combining and merging objects based on a value, I want specific attributes to be concatenated instead of following the default "object on the right wins" rule. check out the demo here In simpler terms, I expect the merge of these two objects [ { ...

Error message indicating that the event "OnkeyDown" is not in sync within the React application

Hey everyone! I'm a beginner in web development and I'm struggling to understand why the event "OnKeyDown" is triggered the second time. My task involves changing (increasing, decreasing) parts of a date (day, month, year, hour, minutes, seconds) ...

Utilize AngularJS to enable the forward and back buttons to fetch JSON data, but ensure that the data is only retrieved if the item meets

I have successfully implemented forward and back buttons for paging through data items in an array from a JSON file: Controller: dishControllers.controller('DrinkcardsController', ['$scope','$http','$routeParams', ...

Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in ever ...

The property for the JQuery keyboard event code is consistently null

Per information from MDN, keyboard events are supposed to have a code property that returns a string constant like "KeyA" if the A key has been pressed. However, in my JQuery keyup event handler, the code property always remains undefined: $(document).on( ...

Issue: The registration token(s) provided for the sendToDevice() function are not valid

Currently, I am working on my final project where I am attempting to send notifications using Firebase Cloud Function when onUpdate is triggered. However, I encountered an error during the process. Despite following tutorials on YouTube and various website ...

Javascript Code. Can you explain what this means: ", (err) => { }"?

I'm a bit puzzled as to how to describe this, so I'm struggling to articulate my question clearly. Can someone please explain what the operator is and what it is accomplishing in this code snippet? My assumption is that it's passing a functi ...

Adjust camera rotation based on specified angle

Looking to rotate an object at a specific angle along the Y axis, I came across a solution on How to rotate a Three.js Vector3 around an axis? which suggests obtaining an updated vector. The code I am using is as follows: var vec = new THREE.Vector3( 0,0 ...

Jquery failing to trigger click() on a div with an id

Within my erb file, there exists a script that looks like the following: function checkJquery() { if(window.jQuery) { jQuery(document).ready(function() { alert('onready'); $('div#habla_topbar_div').click(function( ...

Show or hide the right element when clicked using ng-show in AngularJS

My goal is to toggle elements based on which one is clicked, not all at once. For instance, if I have 3 form elements and 3 buttons, when I click on button 1, I only want to toggle the corresponding form element. Here is my current code snippet: In Angu ...

Updating a useState hook in react with a specific condition: a step-by-step guide

Utilizing react hooks (useEffect and useState) in conjunction with firebase has been a seamless process for me. Having a collection of users that can be easily retrieved from firebase, the basic structure of my code appears as follows: const [users, setUs ...

What method can be used to identify the type of storage: SessionStorage or LocalStorage?

After finding that my variable is of type Storage according to variable.constructor.name, I am now looking for a way to identify whether it is localStorage or sessionStorage. I simply need to retrieve the name. https://i.sstatic.net/kfPYU.png Code exampl ...

Different methods for dynamically altering the style attribute

Here's some code I wrote: <html> <head> <style> .containerTitle { background-color:silver; text-align:center; font-family:'Segoe UI'; font-size:18px; font-weight:bold; height:30px; } ...

Using a comma as a parameter separator is not valid

Having trouble setting up a WhatsApp button with a custom message, I wrote a JavaScript script and called it using onclick. I've tried adjusting quotation marks but nothing seems to be working. This issue might seem minor, but as a beginner in coding ...

Are mutations in Vuex guaranteed to be atomic?

I'm currently investigating the atomicity of mutations in Vuex. The code snippet I'm reviewing has me questioning whether the CHANGE_A mutation could potentially be triggered while CHANGE_B is still in progress: const mutations = { [CHANGE_A]( ...

Retrieving JSON Data using PHP Foreach Loop

I am facing an issue with inserting JSON data into my PHP function. The JSON data is stored in the posts.json file as shown below: NOTE: a1, a11 etc. are just placeholders for demonstration purposes { "posts": [ { "post_name&q ...