How come adjusting the position of my mesh does not cancel out the prior translation?

Delving into the realm of a basic "Hello World" Three.js application has left me pondering over its mysterious workings.

To kick things off, I orchestrate the appearance of a perfectly centered "Hello World" using the following code snippet. This piece of code governs the alignment of the text and nudges it back by 20 units.

/* The Magic is about to Begin */
let loader = new THREE.FontLoader();
loader.load( 'fonts/helvetiker_regular.typeface.json', function (font) {

    /* Bringing Geometry into Existence */
    let geometry_text = new THREE.TextGeometry( "Hello World", {
        font: font,
        size: 5,
        height: 1,
    });
    /* Constructing a bounding box for pinpointing the center location of our textual masterpiece */
    geometry_text.computeBoundingBox();
    let x_mid = geometry_text.boundingBox.max.x - geometry_text.boundingBox.min.x;
    geometry_text.translate(-0.5 * x_mid, 0, 0); // Finding solace in symmetry through offsetting half the width

     /* Slapping on a mere Basic Material due to the absence of light, rendering Phong pitch black */
    let material_text = new THREE.MeshBasicMaterial({
        color: new THREE.Color( 0x006699 )
    });

    let textMesh = new THREE.Mesh(geometry_text, material_text);
    textMesh.position.set(0, 0, -20);

    scene.add(textMesh);
    console.log('mesh integrated')
} );

What fascinates me here is the sequence of events — translation takes the front seat firstly

geometry_text.computeBoundingBox();
    let x_mid = geometry_text.boundingBox.max.x - geometry_text.boundingBox.min.x;
    geometry_text.translate(-0.5 * x_mid, 0, 0); 

and then position swoops in afterwards to displace the mesh

    let textMesh = new THREE.Mesh(geometry_text, material_text);
    textMesh.position.set(0, 0, -20);

The point of contention arises when I remove my translation; suddenly, my serene "Hello World" isn't nestled in the center anymore. Surprisingly, once the translation dance concludes and I assign the position to my mesh as (0, 0, -20), one would assume this positioning directive wipes out my prior translation and hurtles the object to coordinates (0, 0, -20). Why then does my text retain its balance even though set_position prances onto the stage after the translation?

Answer №1

The reason behind this behavior is due to the invocation of THREE.TextGeometry.translate(), which ultimately triggers a call to THREE.Geometry.applyMatrix() with the pertinent translation matrix. This action essentially integrates the transformation by directly adjusting the vertex coordinates. Refer to Geometry.js#L149 for further insights.

To clarify, prior to the aforementioned call:

textMesh.position.set(0, 0, -20);

the mesh's transformation matrix remained as the identity matrix. It's worth noting that mesh transformation differs from geometry transformation in the sense that it solely updates the matrix passed into the shader, instead of recalculating each vertex. When deciding between the two approaches, consider that transforming the geometry incurs higher costs, but executing it once can eliminate the need to repeat it within the render loop (refer to the explanation here).

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

show JSON data following an Ajax request (Asynchronous)

I'm encountering an "undefined" error while attempting to render raw JSON using JSON.parse (result). function decodeVin(result) { var vinArray = JSON.parse(result); var results = "<h4>Vehicle Information Result:</h4>"; results += "Year: ...

The words spill across the navigation bar

I am facing an issue with my navbar where the text overflows and creates extra space due to a white background. I have tried resolving this for a while but haven't been successful. I need help from someone knowledgeable in this area. Here are some im ...

Spring's $.getJSON failing to trigger callback functions

After conducting extensive research, I have come across many similar issues but nothing that has provided a solution to my problem. I am facing an issue where my getJSON call is successfully calling my Spring controller and receiving JSON data in response ...

Deleting a document by ObjectID in MongoDB with Node and Express without using Mongoose: A step-by-step guide

As a newcomer to backend development, I am currently using Node/Express/MongoDB with an EJS template for the frontend. I am in the process of creating a simple todo list app to practice CRUD operations without relying on Mongoose but solely native MongoDB. ...

Javascript did not provide any prompt

I can't seem to get the function to run when I click the link, it only takes me to the link address. (The final alert() function is not executing). I really need that alert message, what am I missing? Below is my code: <html> <head> ...

Tips for incorporating images into an `.mdx` file located outside of the `public/` directory with the `next-mdx-remote` package in Next JS

I am currently developing a blog using next-mdx-remote and I am facing an issue with incorporating images in the .mdx file that are located outside of the public/ folder. If you would like to check out the complete code for my blog project, it is availabl ...

Why is Javascript returning undefined in the alert message?

Why am I getting an undefined result in my alert when running the JavaScript function below: function tabs(data = null){ for(var i = 0; i< data.result.length ; i++){ $.each(data.result[i], function(key, value){ alert(data.result[i].key) ...

Swap out the Vuetify timeline dot for a checkbox

Is it possible to customize the Vuetify timeline circle with a checkbox instead? <div id="app"> <v-app id="inspire"> <v-timeline> <v-timeline-item>timeline item</v-timeline-item> </v-timeline> < ...

Display the webpage exclusively when the application has been set with `app.use('/api')` in Express 4

Here is what I currently have: app.js ... var api = require('./routes/api'); app.use('/', api); app.use('/api', api); ./routes/api ... var router = express.Router(); router.get('/', passport.authenticate(' ...

Transform JavaScript object into desired structure

let obj = { "rec": [{ "id": "25837", "contentId": "25838" }, { "id": "25839", "contentId": "25838" }, { "id": "25838" }, { "id": "25 ...

What is causing the form validation lines to not save and appear after I refresh the page?

Having trouble with the append element in my JavaScript code. Below is the JS file and the corresponding HTML file. JavaScript file: var ck_name = /^[A-Za-z0-9 ]{3,20}$/; var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*& ...

Getting individual user posts sequentially in PHP

As I develop my social networking platform, one challenge I face is how to display user posts individually within a designated div. Similar to Facebook's layout where posts appear one by one and the div expands if the post is lengthy. How can I achiev ...

Validate forms using Joi.js and receive error messages in JSON format

Is it possible to return a JSON object instead of an HTML page when using express-validation and Joi packages for validating forms on the server side? Currently, whenever an error occurs, it returns an HTML page as a response. Route file: // Validator co ...

JavaScript if statement to check for either one, but not both

Hey there, fellow developers. I'm currently encountering a mental block and struggling to find a solution for my issue. Here is the code snippet in question: if ((n % 3 === 0 || n % 5 === 0) &&( n % 3 !== 0 && n % 5 !== 0)) { ...

Making frosted glass effect with three.js in WebGL

Struggling to create a material that resembles frosted glass. Despite searching extensively online, I haven't found a solution that matches my vision. I've experimented with various material settings without success. Check out this link for ref ...

Exploring the capabilities of Angular 10 in conjunction with threex.domevents.js

I'm experiencing difficulties with incorporating threex into my Angular project. Does anyone have experience using this JavaScript library in an Angular environment? ...

Troubleshooting Cross-Origin Read Blocking with the Google Maps Elevation API using Axios in a Vue.js Application

I'm currently working on integrating the Google Maps API into a Vue.js project. I've encountered an issue with two Google Maps services: - The Time Zone API is functioning properly. - However, the Elevation API is giving me a Cross-Origin Read Bl ...

Leveraging jQuery to manipulate an SVG file

jQuery is designed to work within HTML pages that contain JavaScript code. While SVG and HTML both use the same DOM Level 2, SVG is XML-based and employs ECMAScript. What potential issues could arise from utilizing jQuery with SVG? Is it more advisable t ...

Leveraging babel-cli on your local machine

Is it possible to utilize the babel client without the need for global installation? Instead of following this method npm install -g babel-cli I am looking to achieve the same outcome by using npm install babel-cli --save-dev ...

A complete guide on executing synchronous HTTP requests while using async.each in Node.js

My goal is to send HTTP requests to APIs, retrieve data for each user, and then insert that data into MongoDB. The issue I'm facing is that all the requests are being made simultaneously, causing the process to get stuck at some point. I'm using ...