Utilize Three.js to seamlessly incorporate mesh information directly into your code

Here's my Three.js code that loads a mesh from the file /models/mountain.json using a JSON loader:

var Three = new function () {
    this.scene = new THREE.Scene()

    // Camera setup
    this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000)
    this.camera.position.set(20, 52, 20);
    // Camera rotation
    this.camera.rotation.order = 'YXZ';
    this.camera.rotation.y = -Math.PI / 4;
    this.camera.rotation.x = Math.atan(-1 / Math.sqrt(2));
    this.camera.scale.addScalar(1);

    // Renderer setup
    this.renderer = new THREE.WebGLRenderer()
    this.renderer.setSize(window.innerWidth, window.innerHeight);

    var ground = new THREE.Mesh(
        new THREE.PlaneBufferGeometry(436, 624),
        new THREE.MeshLambertMaterial({color: '#808080'}));
    ground.rotation.x = -Math.PI / 2; //-90 degrees around the x axis

    this.scene.add(ground);

    // Point light
    var light = new THREE.PointLight(0xFFFFDD);
    light.position.set(-1000, 1000, 1000);
    this.scene.add(light);

    var loader = new THREE.JSONLoader();
    
    // Load mountain function
    this.loadMountain = function (x, y) {
        loader.load('/models/mountain.json', Three.getGeomHandler('#808080', x, y, 1))
    }

    // Load multiple mountains
    this.loadFields = function () {
        for (var i=0;i<4000;i++) {
            Three.loadMountain(x, y)
        }
    }

    // Geometry handler
    this.getGeomHandler = function (color, x, y, scale) {
        return function (geometry) {
            var mesh = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({color: color}));
            mesh.scale.set(scale, scale, scale);
            mesh.position.set(x, 0, y);
            Three.scene.add(mesh);
        };
    }

    // Initialize Three.js
    this.init = function () {
        $('body').append(Three.renderer.domElement);
        Three.loadFields()
        Three.render();
    }

    // Render function
    this.render = function () {
        requestAnimationFrame(Three.render);
        Three.renderer.render(Three.scene, Three.camera);
    };
}

$(document).ready(function () {
    Three.init();
});

This is the content of /models/mountain.json:

{
    "metadata": {
        "formatVersion" : 3.1,
        "generatedBy"   : "Blender 2.7 Exporter",
        ...
    }
}

Would it be possible to use the content of mountain.json as a variable in our code and add it to the scene?

Answer №1

If you're looking to load a model by parsing a JSON data structure, here's the pattern you should follow.

Start by updating your mountain.json file and assigning a name to your data structure.

var mountain = {

    "metadata": {
        "formatVersion" : 3.1,
        "generatedBy"   : "Blender 2.7 Exporter",

        ... etc ...

}

Add the following code snippet into your source:

<script src="mountain.js"></script>

With this setup, you can now easily load your model as shown below:

var loader = new THREE.JSONLoader();

var model = loader.parse( mountain );

mesh = new THREE.Mesh( model.geometry, model.materials[ 0 ] );

scene.add( mesh );

This solution is tested with three.js r.70 version.

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

Implementing dynamic component swapping in Vue 3 using components from another component

I currently have a display component called app-display, which contains a dynamic component inside (by default, it is set to app-empty): app.component('appDisplay', { template: `<component :is="currentComponent"></c ...

Is there a more efficient method to select all the rows containing '1's in a specific cell within a large range of data?

As a beginner, I've developed a script that scans through a large table and extracts rows containing the value '1'. The table consists of approximately 2000 rows, so it's taking quite some time to process all of them. Is there a more e ...

The process of including a property in Vue.JS

Looking to include this property on my button: uk-toggle="target: #id" The desired outcome is: <button uk-toggle="target: #id" type="button">Click</button> I'm trying to achieve this with Vue.JS but I'm facing some difficulties. H ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

Unraveling intricate JSON structures in PySpark

Having recently ventured into the world of pyspark, I have encountered difficulties in converting a JSON string retrieved from an API call into a dataframe. Despite trying various solutions sourced online, I have yet to achieve success. When I attempt the ...

Tips on saving JSON data in Laravel's MySQL database

I've been experimenting with storing data in a database as JSON, and noticed that the built-in notification table is able to do this. I've created a field of type "text" and am storing data like this (example) {"filenames":["D0BmpFOdyUp4YyA8tqp ...

The reset function in React Native Controller FormData TextInput does not work properly

Encountering an Issue: While on the sensor overview page, I select a specific sensor and proceed to edit its name. Upon saving the changes and navigating back to the list of all sensors, I notice that the updated name has been successfully modified. Howeve ...

Tips for integrating SQL queries into a document that consists mostly of JavaScript and JQuery

I am currently in the process of integrating a SQL database write into my file that is primarily comprised of JavaScript and jQuery. While I have come across some PHP resources online, I am facing challenges incorporating the PHP code into my existing scri ...

Learn how to cycle through three different texts that appear in the same spot using smooth transitions

I am working with three different rows that contain the Typography component. My goal is to display the first row, followed by the second, then the third, and back to the first one in a continuous loop. All three rows should be shown in the same location, ...

Can you please provide instructions on how to expand the view in the title bar for a JavaScript/CSS/HTML UPW project?

Struggling to integrate the title bar in a UWP project using JavaScript/CSS/HTML and having trouble accessing the necessary APIs. Came across a custom helper class written in c++ in UWP samples on Github, but unable to reference it in my javascript code. H ...

I am interested in gradually displaying and then hiding a collection of keywords from an array in a single instance

Experimenting with creating titles that fade in and out on a landing page only once without repeating. I attempted to incorporate a counter variable to ensure the titles stop looping after displaying all items in an array. This method allows for easy add ...

What techniques does Angular2 use to handle dependency injection?

When working with Angular2 components, I know that to inject a dependency, you simply annotate an argument in the constructor, like how ThingService is injected here. However, what I am wondering is how Angular actually knows what to inject at runtime. A ...

Show the user's input on the canvas

Currently, my setup consists of 3 elements - a text field and a submit button at the top, with a canvas below them. I am looking for a way to showcase user input on the canvas after they click the submit button. If you have any JavaScript suggestions, I w ...

A guide on how to insert content into a text area using a drop-down menu choice

I'm a total beginner at this. Is it possible to use JavaScript to automatically fill in a text area on an HTML form based on what is selected in a drop-down menu? If so, can someone please explain how to achieve this? ...

What is the best way to fill in a property for a mongoose schema?

let newPost = new Post({ content: fields.content, creator: req.user, }); newPost.save(function(error) { if(error) { res.status(501).json({ error: error }); } else { res.json({ post: newPost }); } }); The post model has a field called cr ...

Incorporating data into the local storage

Currently, I am utilizing local storage to store JSON data as favorites. However, I have encountered an issue where adding more than one favorite item will overwrite the existing one in local storage. $('.favoritesbtn').click(function() { ...

"When using FireFox, you can easily create a hyperlink that scrolls to a specific section of a webpage,

I have created a style for image button: .sticky { position: fixed; top: 50px; width: 120%; z-index: 1; } @media screen and (min-device-width : 100px) and (max-width: 600px) { .sticky{ display:none; } } and also implemented a script for it: ...

The XMLHttpRequest function consistently comes back as undefined

Currently, I am working on the MDN tutorial about 'XMLHttpRequest'. Unfortunately, when trying to use request.open('GET', url) with a txt file from my local directory, it is returning undefined. I have checked both the url and request i ...

What is the best way to transform a JSON string into a set of key-value pairs?

I am looking to extract all the key-value pairs nested under the "tags" section within "instanceData" and reformat them as direct key-value pairs under "properties". The initial data looks like this... { "id": "/subscriptions/1234abcd-ab12-12ab-12ab-ab ...

Waiting for POST request to be executed once data is inserted

This was a new experience for me; I took a break from working on the project for a while, and suddenly all POST routes stopped functioning. However, the GET routes were still working perfectly fine. After extensive debugging, I discovered that removing the ...