arrange objects based on their position using javascript

In my JavaScript code, I am trying to position objects above each other relative to a center point at coordinates 0,0. The number of objects, their sizes, and the spacing between them are all variable.

This image illustrates my situation best (hopefully ;)): https://i.sstatic.net/IAkw5.png

Here, the green dot represents the center point and the yellow dots represent the mesh center positions.
The Mh indicates Mesh Height (variable)
The Sh indicates Spacing height (variable)
I have attempted to explain the calculation logic for the yellow dots. However, when I try to implement this in JavaScript, it works for 3 lines but breaks with different line amounts.

This is what I have tried so far:

var data = {
    text : ["THE NEXT","POINT","OF VIEW"],
    size : 5,
    height : 2,
    curveSegments : 12,
    line_height : 2
};

function generateTextGeometry(mesh) {

    var scaled_lineheight = map_r(data.size, 2, 75, 0.5, 20);
    var y_start =  (0 - data.text.length * data.size / 2 - data.size / 2 - (data.text.length - 1) * scaled_lineheight)/2;
    var loader = new THREE.FontLoader();

    loader.load( 'data/suisse_2.json', function ( font ) {

        for (var i = data.text.length - 1; i >= 0; i--) {
            var geometry = new THREE.TextGeometry( data.text[i], {
                font: font,
                size: data.size,
                height: data.height,
                curveSegments: data.curveSegments
            });
            geometry.center();
            mesh.children[i].geometry = geometry;
            mesh.children[i].position.y = y_start;

            console.log(mesh.children[i].position);

            if (i < data.text.length) {
                y_start += (data.size + scaled_lineheight);
            }else{
                y_start += data.size;
            }
        }
        console.log('-----------------------');
    });
}

When I log the positions for 3 lines, they appear correct:

p {x: 0, y: -6.301369863013699, z: 0}
p {x: 0, y: 0, z: 0}
p {x: 0, y: 6.301369863013699, z: 0}

But for any other number of lines, the positions are incorrect:

p {x: 0, y: -4.4006849315068495, z: 0}
p {x: 0, y: 1.9006849315068495, z: 0}

My ultimate question is how can I consistently get the yellow positions right relative to the green center? What logic flaw exists in my current approach?

If anything is unclear, please ask for clarification!

Answer №1

Upon the twentieth read of my own inquiry, a sudden spark illuminated my mind.

It turns out, I made an error in my initial calculation. Here is the corrected line:

var y_start =  0 - (((data.text.length - 1) * data.size) + ((data.text.length - 1) * scaled_lineheight))/ 2;

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 challenge with our unique PHP/JS Analytics Solution

Here's an illustration of the code snippet for Google Analytics: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'userIDhere']); _gaq.push(['_trackPageview']); _gaq.push([&apos ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Uneven rotation of objects within the browser

I am currently working on visualizing objects in a web browser. The goal is to display these objects rotating around one axis at a time (either X, Y, or Z) or allow the user to interactively rotate them using their mouse. However, I have encountered severa ...

Is it possible to upload an image file while the element is hidden with "display: none" property?

I need to upload a file using Selenium webdriver. Here is the URL of the page. <div class="async-upload__thumb item-image__area"> <div class="fab-dialog__thumb-drop-zone async-upload__thumb-drop-zone"> <p class="async-upload__thumb-ms ...

Utilizing an automated file retrieval system in the absence of database or website access

I'm faced with a challenge of having to download a file automatically when a user clicks the "ok" button on a website. Unfortunately, I only have access to view the site and do not have access to the database or source code. I'm unsure of how and ...

I encountered an error stating "Module Not Found" while attempting to locate slick-carousel/slick/slick.css. This issue arose while implementing reacy-slick within my Next.js project

While working on my app with Next.js, I wanted to incorporate a carousel like Slick to display images. I followed the official documentation carefully, imported the necessary CSS file, but encountered an error stating "Module Not Found, can't resolve ...

Creating a list of objects in ReactJS

Currently, I am attempting to iterate through object properties (using "Name" as an example) and list them within a loop in a function. The method I have come up with seems quite clumsy and doesn't feel optimal. Here is the code snippet: const Ite ...

avoiding repetition of mouseup event firing

After perusing multiple inquiries on similar matters, I am under the impression that my issue lies in propagation through numerous DOM elements. Despite this, I am still facing the problem of my Ajax function triggering multiple times when the mouseup even ...

What is the best method for selecting multiple images simultaneously in react-js?

I am looking to choose multiple images state = { file: null } handleFile(e) { let file = e.target.files this.setState({ file: file }) console.log('handling file:', file) } If I use an index like this, then I can only upload a sin ...

tips for accessing variables within app.get

Is there a way to make a variable or a set of variables inside app.get accessible throughout the entire project? I am working on capturing information from an SMS text message, organizing it into the "messageData" variable, and then sending it to the "Mess ...

Integrate UploadFS functionality into angular2-meteor

Currently, I am in need of a file storage database and after some research, it appears that UploadFS is the most suitable option for my project. My development involves Angular2 typescript and Meteor. meteor add jalik:ufs-gridfs However, I am encounterin ...

Tips for passing registration form data, uploading images, and implementing validation via Ajax in CodeIgniter

As I work on creating a comprehensive registration form with all necessary data and input tags, I encountered an issue while attempting to pass the image upload value to the next page through AJAX. I need assistance in resolving this problem specifically r ...

An HTML document may display a segment of a URL

Is there a way to display part of a URL in an HTML document, so that if the URL changes, the corresponding content in the body also updates? For instance, www.example.com/?key=i - Is it possible for this link to be dynamically displayed within the body o ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

Mastering TypeScript in Router Configuration

I am currently working with a standard router setup. type Routes = '/' | '/achievements' | ... ; This helps in identifying the routers present in the project. However, I am faced with a new challenge of creating an array that includes ...

Retrieving data from JavaScript global variables within an HTML document using PhantomJS

Recently, I encountered an interesting piece of HTML code that sparked my curiosity: <html> <body> <script> var foo = { bar: [] }; </script> </body> </html> This led me to wonder how I c ...

What is preventing me from displaying the results on the webpage?

Currently, I am utilizing Express alongside SQLite and SQLite3 modules. However, upon running the server, the data fails to display on the initial request. It is only after a page refresh that the data finally appears. I attempted a potential solution by ...

What is the process of inserting a placeholder in an ng-repeat dropdown input field?

I have a situation where I need to implement a drop-down using ng-repeat. The challenge is that I want to include a placeholder in the input box so that it doesn't remain blank when no option is selected from the drop-down. Setting a default placehold ...

Refreshing information using jQuery (AJAX)

Currently embarking on an Ajax learning journey. I need to make some modifications to the data obtained from the server. While I can receive and input the data, I am struggling with saving/editing it. My current approach only allows me to add new records, ...

Having trouble with Node.js GET request functionality not functioning properly

I've been encountering difficulties with loading a page using Node.js. While my Node.js Application code functions properly when attempting to load other resources such as www.google.com, it seems to encounter issues specific to the domain name www.eg ...