A guide on importing JSON files and rendering them in three.js

Greetings fellow developers! I have written some code to import a JSON file and render it using three.js. The JSON file was exported from the three.js editor. Strangely, there are no errors appearing in the console.


        window.onload = function(){
            var shapeObjectUrl = "test.json";
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
            var renderer = new THREE.WebGLRenderer();
            var loader = new THREE.JSONLoader();

            renderer.setSize(window.innerWidth, window.innerHeight);
            document.body.appendChild(renderer.domElement);

            loader.load(shapeObjectUrl, 
                function (geometry, materials) {
                    console.log(geometry, materials);
                    var mesh = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial());
                    scene.add(mesh);
                    console.log(mesh);
                    render();
            });

            camera.position.z = 5;

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

Here is the content of the JSON file:


        {
            "metadata": {
                ...
            }
        }
    

Any assistance with this issue would be greatly appreciated.

Answer №1

Your method is mostly correct, but there are a few minor adjustments that need to be made. For example, in the callback function of the loader.load, you are attempting to access material which is not included in the JSON file.

I tested your code and successfully loaded the JSON object without any issues. However, setting the camera position to 5 may cause the loaded model to be out of view.

To reposition the model, you can use the following code:

var loader = new THREE.JSONLoader();
loader.load( 'models/jsonModel.json', function ( geometry ) {
    var mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );

    mesh.position.x = 500;
    mesh.position.y = 100;
    mesh.position.z = 500;

    scene.add( mesh );
}); 

You can also adjust the camera position or use OrbitControls instead.

I have provided a sample code at this link. You can refer to lines 138 and 62 for a better understanding of the changes made.

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

The Javascript file seems to be unable to recognize the reference to an Angular directive

When working on my project, I encountered an issue with my EventController.js not recognizing the reference to ng-app="eventsApp" from app.js. I followed a tutorial on Pluralsight. Even though it works for the instructor, I keep seeing {{event.name}} inst ...

Exploring Meta Data Updates in a React Server-Side Rendering Application

I'm in the process of developing a react application and encountering some challenges... I've set up the server-side rendering of my page using this code snippet... const router = express.Router(); router.get('/homepage', (req, res) ...

Connect to Node-Red websocket server

My server is running node-red with embedded functionality. I am attempting to set up a new websocket listener on the server, but when I run the code provided, the websockets in my node-red application stop functioning properly. const WebSocket = require(& ...

.NET API encounters issues with long JSON strings being shortened when returned

I have a stored procedure in SQL Server that generates JSON using FOR JSON. When I execute the procedure directly in SQL, it returns the JSON correctly and I can validate the output using tools like jsonlint. However, when the procedure is called from a .N ...

Is there an optimal method for passing an associative array through the map/reduce function in MongoDB?

Below are the functions I have written: map: function () { // initialize KEY // initialize INDEX (0..65536) // initialize VALUE var arr = []; arr[INDEX] = { val: VALUE, count: 1 }; emit(KEY, { arr: arr }); } reduce: function (key, values ...

Creating a conditional npm script that depends on the output of another: a step-by-step guide

I've encountered this problem before while setting up npm scripts, and I haven't been able to find a solution yet. I'm hoping to make the solution compatible with both Mac and Windows environments. I'm working on splitting up the logic ...

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Limit the ng-repeat directive based on the length of the array, using an ng-if condition

<div ng-repeat="badgesData in deptUSersData.badges | limitTo : 7 track by $index"> ........content....... </div> If the length of deptUSersData.badges is more than 8, I want to apply a limit of 7. How can I achieve this? My desired ...

What is causing Vuejs to not recognize the status of my button?

I am currently developing a Vuejs website that allows users to jot down notes about meetings. Upon loading, the website fetches the meeting notes from the server and displays them. When a user adds new notes and clicks the "Save" button, the text is saved ...

node.js experiencing crashing following loop iteration

I'm currently developing a performance testing tool using node.js to automate the process and store the results in MySQL. This tool is designed to track the load time of specific web pages in a browser, with the measurement displayed in seconds. I am ...

Display various React components for widgets

I am looking to display multiple instances of a widget in html. I have 3 divs with the same id, each with different attributes, and I want to render my react component three times on the page. Currently, I am only able to display the first component. Here ...

Ways to achieve combined outcomes using ng-repeat

Check out this plunker. <div ng-repeat="subCategory in subCategorys | filter:{tags:tag}:true | orderBy:'id'"> {{subCategory.id}} {{subCategory.name}} {{subCategory.tags}} <br/><br/> The detailed information of ...

Understanding the usage of JSON in representing foreign key relationships

Imagine I have a scenario similar to the one in the provided document: class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __unicode__(self ...

Storing JSON data in list items within an HTML document using React

I am currently working on creating a component that can provide auto-suggested values from an online API and then send the value and its associated JSON data back to the parent component. So far, I have successfully implemented a feature that generates a ...

Tips for creating text that adjusts to the size of a div element

I'm currently working on developing my e-commerce website. Each product is showcased in its own separate div, but I've encountered a challenge. The issue arises when the product description exceeds the limits of the div, causing it to overflow ou ...

Guide to achieving a powerful click similar to a mouse

I've been struggling to get an audio file to play automatically for the past three days, but so far I haven't had any luck. The solutions I've tried didn't work in my browser, even though they worked on CodePen. Can anyone help me make ...

Facing Issues with Angular 10 Routing on an HTTP Server Deployment?

After successfully running my Angular ver-10 Ecommerce Project locally with "ng serve", I encountered an issue when trying to publish it using "ng-build" and hosting it with "http-server". The problem arises when navigating from the Home Screen (e.g. Dashb ...

It appears that the home page of next.js is not appearing properly in the Storybook

Currently, I am in the process of setting up my next home page in storybooks for the first time. Following a tutorial, I successfully created my next-app and initialized storybooks. Now, I am stuck at importing my homepage into storybooks. To achieve this, ...

Employing asynchronous operations and the power of async/await for achieving seamless integration

I am currently facing an issue where I need to retrieve queries from a database stored in Postgres. A function is utilized, which employs a callback mechanism. In order to fetch rows from the database, there exists a function called getRecipesByCategoryFo ...

Why are the values in my options created using the array map method empty in React?

I decided to use a for loop to generate an array containing the numbers 1 through 12 representing each month. I then attempted to utilize the map array method to create 12 options, but unfortunately they are coming up empty. Below is a snippet of the ...