Modify the JSON object once it has been imported into Three.js

I am diving into the world of JavaScript and exploring Three.JS, a fascinating new frontier for me. Recently, I managed to convert an obj file into a JSON object and successfully loaded it onto my website using THREE.JSONLoader in three.js. The object displays flawlessly as intended, but now I find myself wanting to interact with it further - rotate, animate, manipulate like any other THREE.Mesh Object would allow. My initial attempt was to mimic the rotation and animation of a cube demonstrated in the very first three.js tutorial, specifically focusing on a mesh chair. However, when I tried to implement the rotation within the "animate()" function after loading the object, I encountered an error claiming that my variable, "myChair", is undefined:

myChair.rotation.x += 0.1;

I suspect there might be an additional step required for three.js to recognize this JSON data as a genuine THREE.Mesh object?

Below is the code snippet:

viewport = document.getElementById('mycanvas');
h = viewport.offsetHeight;
w = viewport.offsetWidth;
var scene = new THREE.Scene();
scene.background = new THREE.Color( 0xffffff );
var camera = new THREE.PerspectiveCamera( 75, w/h, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize(w, h);
viewport.appendChild(renderer.domElement);

//end viewport

var myChair = new THREE.JSONLoader();
myChair.load(
'https://api.myjson.com/bins/iaxn7',
function ( geometry, materials ) {
var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
var object = new THREE.Mesh( geometry, material );
scene.add(object);
}
);

alert(myChair); //this alert confirms that an object is stored in the variable 

var animate = function () {
  requestAnimationFrame( animate );

  myChair.rotation.x += 0.1;
  myChair.rotation.y += 0.1;

  renderer.render(scene, camera);
};

animate();

Thank you for any guidance or assistance offered! Your help means a lot.

UPDATE: following Marco's advice.

 var myChairLoader = new THREE.JSONLoader();
 var chairMesh = null;

myChairLoader.load(
'https://api.myjson.com/bins/iaxn7',
function ( geometry, materials ) {
var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );
var chairMesh = new THREE.Mesh(geometry,material);
scene.add(chairMesh);
    renderer.render(scene,camera);
}
);

var animate = function (){
  requestAnimationFrame(animate);

  if(chairMesh !== null){
    alert();
    chairMesh.rotation.x += 0.1;
    chairMesh.rotation.y += 0.1;
  }
  renderer.render(scene,camera);
};

animate();

Answer №1

You are trying to animate myChair, which is a THREE.JSONLoader object and cannot be animated. Instead, you should be animating the Mesh named object that you have added to the scene. I suggest updating your code as follows:

var chairLoader = new THREE.JSONLoader();

// 1: This will remain null until the JSON file is loaded
var chairMesh = null;

chairLoader.load(
    'https://api.myjson.com/bins/iaxn7',
    function ( geometry, materials ) {
        var material = new THREE.MeshBasicMaterial( { color: 0x0000ff } );

        // 2: When the JSON is loaded, convert it into a Mesh using the variable above
        chairMesh = new THREE.Mesh( geometry, material );

        // 3: Add it to the scene
        scene.add(chairMesh);
    }
);

alert(chairLoader); //This loader is not for the chair you want to animate.

var animate = function () {
    requestAnimationFrame(animate);

    // 4: Only animate chairMesh after the JSON has been loaded
    if(chairMesh !== null){
        chairMesh.rotation.x += 0.1;
        chairMesh.rotation.y += 0.1;
    }

    renderer.render(scene, camera);
};

Take note of the chairMesh variable - that is the one you should animate and add to the scene.

On a side note, avoid using the variable name object as it's a reserved keyword in JavaScript and can cause confusion. It's similar to naming a variable string, which can create ambiguity.

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

calculate the total value of a series of numbers within an array

function createRange(start, end) { var numbers = []; for (var i = start; i < end + 1; i += 1) numbers.push(i); return numbers; function calculateSum() { numbers.reduce(function (a, b) { return a + b; } ...

What is the best method for transferring JSON between two Node servers for optimal efficiency?

I am at an intermediate level in node.js and I need to transfer JSON data from one independent server to another independent server. The size of the JSON data can range from 200 bytes to 50 kilobytes, with up to 500 requests per second. Initially, I was u ...

Error encountered: TypeError: Unable to access attributes of null object (attempting to read 'useMemo')

In the development of a public component titled rc-component version0.1.14, I built a platform that allows for the sharing of common React pages amongst various projects. However, upon attempting to utilize this component in my project, I encountered the f ...

jsTree open_all not triggering consistently

Upon receiving x number of projects and their corresponding directory structure from the server in a single AJAX call, the connection is disconnected from the server. Subsequently, all operations must be carried out from the browser. After loading the pro ...

Can you suggest an alternative for the "return" statement within a "for loop" in order to retrieve all values from the loop?

When using numInOrder + " : " + nameInOrder;, the console only displays one value: "1 : a". However, I would like to see: "1 : a 2 : b 3 : c 4 : d 5 : e 6 : f" in the console.log output. Additionally, I do not want to use consol.log(numInOrder + " ...

Can someone explain how to replicate the jQuery .css function using native JavaScript?

When referencing an external CSS file, the code may look something like this: #externalClass { font-family: arial; } Within the HTML file, you would use it like so: <a href="#" id="externalClass">Link</a> In the JavaScript file, you can ret ...

Retrieving Key-Value Pairs with the Assistance of the Lodash

My JSON Object contains the following data: { "data":[ { "customer":101, "profile":7, "context":{ "rows":20, "from":"2016-01-05T06:14:02.750Z", "filter_group_id":null, ...

The synchronization of user permissions in Meteor.js seems to be out of sync with the

As a newcomer to the world of meteorjs and MongoDB, I am currently navigating through "Getting Started with Meteor.js JavaScript Framework" by Isaac Strack. However, I have hit a roadblock in chapter 6 titled "Granting admin permissions." Despite following ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

Removing an item from an array using AngularJS with Underscore or another method

Although my question may seem similar to others, it is unique! Please review to understand my specific situation. I am dealing with an array of objects that looks like this $scope.events =[ { $$hashKey: "009" _allDay:false _i ...

The PHP function is failing to communicate with jQuery and Ajax

Having trouble with PHP return to jQuery/Ajax functionality, When I try to edit an item, the error message displays even though the success function is executed. On the other hand, when attempting to delete an item, nothing is displayed despite the succes ...

Transmitting and receiving a blob using JavaScript

Is there a way to send a blob using a JQuery ajax request and receive it server-side with Node.js + express? I tried sending the blob as a JSON string, but it doesn't seem to include any of the binary data: {"type":"audio/wav","size":344108} Are th ...

JavaScript for Designing in Two and Three Dimensions

I need to take a 2D design created in microstation and display it on the web using a tool like javascript, Unity 3D, or another similar option. The web tool should have basic functionality like reshaping or adding new shapes. My current approach involves c ...

What is the best way to format a date input field so that when a user enters a year (yyyy), a hyphen (-

Need help with date formatting in the format yyyy-mm-dd. Seeking a way to prompt user input for the year and automatically append "-" to the date as needed. Also utilizing a datepicker tool for selecting dates. ...

The loading status will be updated once the data has finished being fetched

I have two action creators in my code - one for fetching data from an API and the other for managing the loading status. However, I am facing an issue where the loading status changes to false before the data is completely fetched. Here are the relevant p ...

Using data attributes to store HTML content within Reactjs components

I am struggling to understand how one can utilize HTML within a data attribute in React's jsx. For example: data-bs-template='<div class="tooltip d-none d-md-block" role="tooltip"><div class="arrow">< ...

Easy method for importing videos into NextJs

Import Coding Guidelines Encountering an error after importing the code, unable to find any solutions online ...

Python error: Index out of range when utilizing index() function

@bot.command() async def start(ctx): edit = [] with open("wallet.json", "w") as file: for obj in file: dict = json.load(obj) edit.append(dict) userid = [] for player in edit: user ...

Switch Selector for React Native

Although it may seem simple, I'm having trouble getting a function to automatically switch between the "user" and "business" options on the switch selector without requiring manual input from the user. I attempted to use: const switchRef = useRef(nu ...

Tips on Eliminating the Gap Between Input Fields in JQuery Mobile

Currently utilizing Cordova and JQuery Mobile for my project. I am in the process of creating a settings page with multiple input fields. My goal is to eliminate the spacing between the rows, but I have been unsuccessful in finding a solution. https://i. ...