Tips for capturing the Three.js model file content and assigning it to a variable

After exporting a model from Blender to Three.js, the resulting file contains JSON data. There are two methods I know of for loading this model:

var loader = new THREE.JSONLoader()
var material = new THREE.MeshPhongMaterial({color: '#8080a0'})

1.

loader.load('tower.json', function (geometry) {
    var mesh = new THREE.Mesh(geometry, material)
})

2. Make changes to the tower.js file by adding

var tower = 

on the first line. Then load it using:

var towerModel = loader.parse(tower)
var mesh = new THREE.Mesh(towerModel.geometry, material)

I personally prefer the second solution as repeatedly using loader.load() when creating multiple meshes based on the same model can significantly slow down performance and potentially crash your browser.

Therefore, my question is - is there a way to extract JSON data from the tower.json file directly into a variable without manual alterations? The ideal scenario would be to retrieve the JSON data without having to modify the file itself.

Answer №1

Option 1 seems like the way to go in my opinion. It doesn't make much sense to include a loader in a source file. To maintain organization, it's better to keep loaders and data sources (such as model files) separate.

Why bother reloading the same model? It's more efficient to store it in a variable and reuse it instead of loading the same geometry multiple times which can be taxing on both CPU and memory.

Here's an optimization concept you can try out:

// Keep track of model files
myFiles = {
    tower: 'tower.json',
    car: 'car.json'
};

// Store loaded geometries
myModels = {
    tower: null,
    car: null
};

// Loader function that loads from file or storage
var load = function( modelName ){
    if( myModels[modelName] === null ){
        loader.load(myFiles[modelName], function (geometry) {
            myModels[modelName] = geometry;
        });
    }

    var model = new THREE.Mesh(myModels[modelName], material)
    scene.add( model );
}

Feel free to adjust this code according to your preferences.

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

Dropbox menu within an extended webpage

I am looking to create a dropdown menu that behaves like the one on this website. The goal is for the dropdown to cover the entire webpage, hide the scroll bar, and "unmount" the other elements of the page, while still displaying them during the transition ...

Modify the dateFormat setting in amChart to display the dates as the days of the week, such as Monday

Struggling with altering the date format in my chart code. I'm unable to change it from years to my preferred week days like Mon or Tue. Here is my chart code: <div id="chartdiv"></div> <script> ...

Activating view loading in AngularJS through child window authentication (OAuth)

I have tried implementing OAuth in AngularJS using Hello.js following what I believe is the best practice. However, I am encountering some issues with my current approach as described below: After injecting Hello.js into Angular and setting up the OAuth p ...

Combining user input data using JavaScript and Vue.js

I am working on a form using Vue.js and I want to combine the data from the input fields upon submission. I have been struggling to achieve this and created a jsfiddle to showcase my attempt. In my form, I have three Vue components for each of the input f ...

Learn how to access a variable within the Watch function using a directive in Angular framework

I'm new to Angular and encountering some issues with the watch function. I am trying to track changes in a variable inside a controller, and once the value of this variable changes, I want to pass that updated value to a directive. Below is the code ...

NodeJS Jest test failing due to a global variable being set for a different test already

I am currently working on a project in TypeScript using Node.js and Jest. I have a function that may or may not modify a global variable, which is a TypeScript Map. After one test modifies the global variable, it retains that value for subsequent tests. I ...

Looking for assistance in consolidating identical values in a dictionary into one cohesive group

I am working with a json file that has specific data formatting. { "courses": [ { "professors": [ { "first_name": "Zvezdelina", "last_name": "Stankova", "p ...

Guide to encoding data using a multidimensional array in JSON format

I have an array that looks like this: array { [0] => {"ID":"343","name":"John","money":"3000"} [1] => {"ID":"344","name":"Erik","money":"2000"} [2] => {"ID":"346","name":"Ronny","money":"3300"} } My goal is to transfer this data from ...

Upon clicking the button, input numbers into multiple number type inputs

I recently implemented a button in my application that increments the value of input type='number' after it is clicked. While everything seems to be working fine, I noticed that the numbers start from 0 instead of 1. Is there a way for me to ens ...

Write the dictionary data directly to a file without any additional processing

Can the json module be used in this way? >>> import json >>> d={1:2} >>> json.dump(d, 'file.json') Alternatively, is it necessary to utilize json.dumps and then file.write? Like so: >>> open('file.json& ...

Tips for changing the <title> in an AngularJS one-page application

I am working on a single-page AngularJS application. The index.html file is structured as follows: <html ng-app="myApp" ng-controller="MyCtrl as myctrl"> <head> <link rel="stylesheet" href="my-style-sheet.css"> <title>{{ ...

Having trouble getting async and await to function properly

Why is my code not waiting for validation and running the else part immediately? Can you help me find the mistake? async validateBeforeSubmit(event) { await this.$validator.validateAll().then(result => { if (result) { ...

Measuring the success of Vuejs app

Seeking performance metrics for a Vue application. Interested in metrics for the entire app as well as specific components. I am aware of using Vue.config.performance = true; to enable performance monitoring through dev tools, and I have considered utiliz ...

The action of json_decode/encode on a simpleXMLElement results in the addition of arrays instead of leaving empty strings

When processing an XML document and converting it to an array using json_decode(json_encode(simplexml_load_string($xml)), 1); All empty XML nodes (<node />) are currently transformed into arrays, but I want them to be represented as empty strings. ...

Having trouble running Protractor with the Angular Seed Basic app in AngularJS?

After cloning the angular-seed to my basic setup, I attempted to run protactor using the command below and encountered an error: npm run protractor npm ERR! node v5.0.0 npm ERR! npm v2.10.1 npm ERR! code ELIFECYCLE npm ERR! [email protected] protr ...

What is the significance of the "@" in JXON conversion in JavaScript?

Looking at an XML structure like the one below: <calendar> <month year="2013" num="5"> <day num="1"> </month> </calendar> I decided to convert it to JSON using MDN's JXON Snippet 3. https://developer.moz ...

Instructions for showing a timer on a webpage from a managed bean by utilizing JavaScript

I'm currently tackling the challenge of passing a Date from a managed bean to JavaScript and then displaying it as a timer in the format "hh:mm:ss aa". I've attempted it but so far, no luck. Code: DateTimeManagmentMB.java (Managed Bean) import ...

When using jQuery to focus on an input element, the cursor fails to show up

Looking to enhance user experience by focusing on an input element upon clicking a specific div. The HTML structure being used is as follows: <div class="placeholder_input"> <input type="text" id="username" maxlength="100" /> <div ...

Is there an issue with my JavaScript append method?

Within the following method, an object named o gets appended to a list of objects called qs. The section that is commented out seems to be causing issues, while the uncommented section is functional. What could possibly be wrong with the commented part? on ...

Encountered an error while trying to run npm start

I set up a Vagrant virtual machine, installed Node.js (v 6.9.1), and NPM (v 4.0.0). After cloning a Node.js app using Git clone, I ran the npm install command in both the root folder and the app folder. However, when attempting to start the app with npm st ...