A guide to correctly importing a Json File into Three.js

I've been working on some cool projects in Blender and wanted to showcase one using threejs. However, I'm facing an issue where the object isn't displaying properly. Can someone guide me on how to correctly load a JSON file with keyframe animation?

I have the specific JSON file here that I need help loading.

Below is an excerpt of the code that I am currently using:

var mesh;
function initMesh() {
    var loader = new THREE.JSONLoader();
    loader.load('./ocean.json', function(geometry, materials) {
        mesh = new THREE.Mesh(geometry, new THREE.MeshFaceMaterial(materials));
        mesh.scale.x = 0.75;
        mesh.scale.y = 1;
        mesh.scale.z = 0.75;
        scene.add(mesh);
    }, undefined, function (e) {console.log('ERROR: ', e)});
}

Answer №1

If you're looking to dive into Three.js, a great starting point is their editor tool which you can find at:

The editor provides a user-friendly interface where you can easily import .json, .obj files, and more. It's a convenient way to visualize your creations, experiment with lighting, play around with materials, incorporate custom scripts, and much more. One useful feature is the ability to load an example project, remove default elements, import your own model, hit play, and if you're satisfied with the result, simply publish the project. This allows you to download the complete project package which can then be uploaded to your server as the foundation for future projects.

Starting with the editor is ideal for beginners as it functions smoothly and serves as a motivating platform for further exploration and learning.

While this may not directly address your query, I've encountered the frustration of dealing with incompatible loaders due to oversights like incorrect checkbox selections during exporting from software such as Blender. The editor eliminates such issues by offering a straightforward environment for creating and testing your Three.js projects.

My advice would be to familiarize yourself with the editor first, understand its features, and progress from there. Good luck on your Three.js journey!

Answer №2

Ensure proper rendering.

let scene, camera, renderer, controls;

// include stats for performance tracking
stats = createStats();
//document.body.appendChild(stats.domElement);

scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
camera = new THREE.PerspectiveCamera(2.5, window.innerWidth / 
window.innerHeight, 1, 1000);


renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

//Triggering EventListener...
document.addEventListener('message', function(e) {
    let message = JSON.parse(e.data);
      if(message.type === 'xyz.json' || message.type === 'abc.json' || message.type === 'mno.json') {
        let modelName = `model/${message.type}`
        var objectLoader = new THREE.ObjectLoader();
        objectLoader.load(modelName, function(obj) {
          scene.add(obj);
          render();
          /* Handle react-native specific actions with below code block.
          awaitPostMessage();
          window.postMessage(JSON.stringify({
            type: 'READY_TO_RENDER'
          }), "*");
          */
        });
      }
 });//EventListener method Ends Here...


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

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

Issue encountered in Next.JS when attempting to validate for the presence of 'window == undefined': Hydration process failed due to inconsistencies between the initial UI and the server-rendered

I encountered an issue that says: Hydration failed because the initial UI does not match what was rendered on the server. My code involves getServerSideProps and includes a check within the page to determine if it is running in the browser (window==&apo ...

Tips for maintaining consistent header and footer while developing the front end using JavaScript

Is it possible to maintain the same header and footer on all pages of a website if using JavaScript for the front end and PHP for the back end? While I am comfortable doing this with PHP, I am curious if it can also be achieved with JavaScript or HTML, o ...

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...

Retrieving custom data attributes from slides within a slick carousel

After the recent Slick carousel update to version 1.4, there have been changes in how data attributes are accessed from the current slide. The previous method that was working fine is as follows: onAfterChange: function(slide, index) { $('.projec ...

What sets apart .addEventListener and .on() when it comes to including an event in Bootstrap 5?

I'm currently attempting to attach a listener to my modal in order to implement a certain behavior each time the modal is opened. As per the guidance from Bootstrap 5 documentation, you can achieve this by using: https://getbootstrap.com/docs/5.2/com ...

When integrating react-hook-form with Material-UI TextField in a form, an error occurs stating that "TypeError: e.target is undefined" when

Hey there, I stumbled upon something fascinating and could really use some assistance. Every time I attempt to perform an onChange, I run into the following error: TypeError: e.target is undefined. Here's a snippet of my setup: import React, { useE ...

Can REST calls be initiated when the CSP is unable to be modified from the default-src: 'none'?

Sometimes, I wonder if this question is silly because it goes against the purpose of the Content Security Policy. There's a webpage located at foo.baz.com that requires data from bar.baz.com to function locally. Below is the code snippet for the func ...

Is it possible to prevent the text from appearing in the text box when a button is

I have successfully implemented a feature where clicking on the button (click on me) in HTML displays a textbox along with another button (show) on the screen. The text written in the textbox is visible when the show button is clicked. However, after the i ...

A common challenge in React is aligning the button and input line on the same level

I'm currently working on a React page where I have an input field and a button. My goal is to align the bottom edge of the button with the bottom line of the input. Here's the code snippet I have: `<form className='button-container'& ...

When attempting to access the Angular app in Edge, it automatically redirects to open in IE 11 instead

I have encountered an issue with my angular 5 App. It works perfectly fine in Chrome and Firefox, but when I try to open it in Microsoft Edge on Windows 10, the application always opens in the IE 11 browser. There are no errors displayed on the console. W ...

Why do React components require immutable props when values are passed by value regardless?

I am not deeply knowledgeable in JavaScript, so I have been experimenting with some code: var demo = 'test'; var obj = { x: 'abc' } function foo(str) { str += '_123'; ...

Is it possible to identify users using an iPhone while they are utilizing "Private Browsing" mode?

Looking for a solution to detect private browsing mode in my jquerymobile App. I need localStorage and sessionstorage to work properly, but prompting users to enable cookies when private browsing is enabled doesn't solve the issue. Is there a way to t ...

Ways to prompt a specific text value to generate varied responses

Whenever I try to input the letter "h", I expect a specific value in return but for some reason, it's not working as intended. Despite my best efforts to troubleshoot the issue, I have been unsuccessful in finding a solution. It's frustrating bec ...

Issue: Unspecified error when trying to access object attribute in Vue (Nuxt)

I am facing an issue with my 'region' object. It appears to be displayed correctly with all its attributes, but when I try to access specific attributes, it shows up as 'undefined'. const region = { "id": 7, "name": ...

Adding an active class to a large image when a thumbnail image is clicked can enhance user experience and

I've created a photo gallery using jquery. Currently, when I click on "next", the image changes based on the index. However, I also want to be able to click on the thumbnails (small images) and display the larger image according to that specific inde ...

Cease running code post while loop (do not use break)

I need help with my code that checks if a user is already in a Database. Once the while Loop runs, it verifies the presence of the MC Player in their Database through the Mojang API. However, if the user is already in my Database, I want to skip the Mojang ...

Concentrate on the disappeared div element following the AJAX request

Encountering an unusual issue here that has me a bit puzzled. In one of my DIV elements, I have included several links which trigger an AJAX call (using jQuery) upon being clicked. The server (Controller) then responds with HTML content, specifically a JS ...

How do I repeatedly invoke a function in JQuery that accepts two different arguments each time?

I have a collection of folders, each containing various images. The number of pictures in each folder ranges from 8 to 200. Folders are numbered from 1 to 20 and the images within them are also labeled numerically. My goal is to aggregate all these images ...

prompting the JavaScript hangman game to identify the letters in the "selected word"

Currently, I am on a mission to teach myself Javascript and have taken on the challenge of creating a simple hangman game. This type of project is commonly used in interviews or tests, so it seemed like a great opportunity for practice. My approach involve ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...