Learning to retrieve and save information from an external file and assigning them as variables in JavaScript using three.js

As a newcomer to three.js, I'm still figuring things out and may be treading familiar ground with this query. Here's the situation: I've got an external .txt file that lays out the x, y, z positions for 256 atoms. The opening lines of said .txt file look something like this:

256
1 0.702825 2.71217 2.71612
1 16.9592 2.64886 6.79019
1 0.681418 2.68359 10.8911
...

The initial row reveals the atom count in the compound and the first column signifies atomic size, while the remaining figures represent the x, y, z values for each individual atom. As of now, I've manually inputted the position of the first atom as follows:

...
scene.add(sphere); 
sphere.position.set(0.702825, 2.71217, 2.71612);

My goal is to read through the .txt file line by line and extract subsequent x, y, z positions into variables. How can I leverage the details stored in the external file?

Answer №1

  • To retrieve the contents of a file, consider utilizing AJAX technology.

    For example: Check out this answer on SO.

  • Once you have obtained the file data, you can use the String#split function to segment it into lines and columns.

    For example: Refer to this SO post

  • Finally, you can treat the data as an Array.

Answer №2

Utilize the power of the fetch API:

fetch('myfile.txt').then(response => response.text()).then(text => {
  const elements = text.split('\n')  
    .map(line => line.trim())     
    .slice(1)                     
    .map(line => line
      .split(' ')                 
      .map(Number))               
    .map(([size, x, y, z]) => ({ size, x, y, z })); 
});

elements will now hold data like this:

[
  { size: 1, x: 0.702825, y: 2.71217, z: 2.71612 },
  { size: 1, x: 16.9592, y: 2.64886, z: 6.79019 },
  ...
]

You can easily incorporate this into your Three.js project.

To iterate through the elements, you could do the following:

elements.forEach(({ x, y, z }) => { 
  // ...
  sphere.position.set(x, y, z);
  // ...
});

or:

elements.forEach(atom => { 
  // ...
  sphere.position.set(atom.x, atom.y, atom.z);
  // ...
});

or:

for (let i = 0, len = elements.length; i < len; i++) { 
  // ...
  sphere.position.set(elements[i].x, elements[i].y, elements[i].z);
  // ...
}

Alternatively, you can use XMLHttpRequest instead of the fetch API.

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

What could be the reason behind receiving information from a mongodb database that seems to be empty?

I have been working on a todo application, and I am facing an issue with the ng-repeat directive in my code. It seems to create five todo boxes even when the database is empty. This may be related to the loadData function that I am calling, but I am unable ...

Getting data from a wordpress database using javascript

After setting up a table named inspirationWall in my database with id and Visit_Count as INT, I inserted a row with id=1 and Visit_Count = 2. Now, attempting to fetch the Visit_Count value in WordPress and show it in an alert for testing purposes. I have ...

Converting an onclick event to onsubmit: Tips for doing it right

Recently, I had to add validation to a file upload form for our Google Drive. After some research, I discovered that using onsubmit instead of onclick was the way to go. However, when I made the switch from onclick to onsubmit, the validation worked but t ...

I'm encountering an error when attempting to serve a static file for two different routes in node.js while using the sendFile() method. What's causing

I attempted to send a static HTML file for two different routes: '/' and '/test'. While it is functional for the '/' route, the same does not apply for the '/test' route. Upon inspecting further, I encountered the f ...

What is the process for removing items from an array in JavaScript that share the same values?

If you have an array of objects structured like the following: "medios":[ { "Key":"1", "Text":"Cheque" }, { "Key":"2", "Text":"Tarjeta de Crédito" }, { "Key":"3", ...

Vue looping through nested checkbox groups

Here is an object I am working with: rightGroups: [ { name: "Admin Rights", id: 1, rights: [ { caption: 'Manage Rights', name: 'reports', ...

What is the best way to assign Reference Identification numbers to the orders?

Is there a way for me to obtain and attach the id reference to the order? I have retrieved the product and user ids. When I utilize my get method, it should retrieve all the details about the products and users. For instance, the data will display compreh ...

Heroku is rejecting the Discord token, but it is functioning properly in Visual Studio Code

I am facing an issue with an invalid token error on Heroku, even though the token in my main.js file on Git is the same as the one I have in Visual Studio Code. Interestingly, Heroku claims it's an invalid bot token while the Discord bot token from VS ...

Struggling with navigating segmented dropdown buttons

I was following a tutorial on Udemy to learn about inputs and dropdown buttons for bootstrap. Everything was going well until I attempted to create a simple selection of albums for one of my favorite artists. The buttons kept separating when I tried to cen ...

Issue encountered when attempting to assign an action() to each individual component

I'm facing an issue with the button component I've created. import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-button', template: ` <ion-button color="{{color}}" (click)="action()"&g ...

Show the name of the channel on the FeatherJS chat application

I've been using this repository as a guide to develop a chat application. Currently, I'm working on displaying the channel name (the default room where users are logged in) in the chat client. Is there a way to retrieve channel information from ...

Utilizing Vue.js for enhanced user experience, implementing Bootstrap modal with Google Maps autocomplete

I recently set up a Bootstrap modal that includes an <input>. To enable Google autocomplete for it, I utilized the commonly known trick below: .pac-container { z-index: 10000 !important; } However, I have encountered difficulty in getting the a ...

Aligning a picture at the center of the screen with CSS - Various screen and image sizes

For my project, I need to design a web page with a single image perfectly centered both vertically and horizontally on the screen. Here are the specific requirements: The client's screen size is unknown (mobile) The image will be user-defined with u ...

The jQuery fadeOut function modifies or erases the window hash

While troubleshooting my website, I discovered the following: /* SOME my-web.com/index/#hash HERE... */ me.slides.eq(me.curID).fadeOut(me.options.fade.interval, me.options.fade.easing, function(){ /* HERE HASH IS CLEARED: my-web.com/index/# * ...

What is the method for triggering the output of a function's value with specified parameters by clicking in an HTML

I am struggling to display a random number output below a button when it is clicked using a function. <!DOCTYPE html> <html> <body> <form> <input type="button" value="Click me" onclick="genRand()"> </form> <scri ...

Adjust the playlist based on the spinning motion using jQuery

Can I restrict playing French music only when the "world" angle is between 0 degrees and 27 degrees? The world rotates based on scrolling. Thank you, everyone :) $(document).ready(function() { var angle, scroll = 0; var $world = $('#world'); var ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Diving deep into the reasons behind a test's failure

Currently, I am using Postman to test the API that I am developing with express. In this process, I am creating a series of tests. Below is a brief example: tests["Status code is 200"] = responseCode.code === 200; // Verifying the expected board var expe ...

I have a requirement in my Angular application where I need to display two columns, however, the content within those columns may differ based on the route. What is the best approach to

I have a requirement in my app where I always need two columns, with one being slightly smaller than the other. Currently, each of my routes directs to a different component which provides the markup for these columns in its own template. However, since th ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...