Getting the barycentric coordinates of a triangle within a mesh using Three.js: A detailed guide

Currently using r71, I am facing a challenge where I need to click to raycast and scale a THREE.Geometry plane based on a user uploaded image. Additionally, I am looking to retrieve the barycentric coordinates of a point inside the clicked triangle on the mesh. Although there is a function called

THREE.Triangle.barycoordFromPoint (point, optionalTarget)
, I am not achieving the desired outcome possibly due to the scaling of the mesh according to the uploaded image.

var scaleRatio = 0.1;

var loader = new THREE.OBJLoader();

loader.load( 'obj/plano_tri.obj', function(object) {

    var scaleTexture = 1;

    var scaleGeometryX = texture.image.width / texture.image.height ;

     var desiredHeight = 144 * 0.08;

     if (texture.image.height > texture.image.width) {

          scaleTexture = desiredHeight / texture.image.height;

     }

      var plane = object;

      plane.scale.setX( scaleRatio * scaleGeometryX );

      plane.scale.setY( scaleRatio );

      scene.add( plane );

   });

My approach involves converting the Face3 indexes acquired through raycasting into a triangle and then invoking the function with the point from the raycast:

raycaster.setFromCamera( mouse, camera );

intersects = raycaster.intersectObject( plane, true );

var face = plane.geometry.faces[ intersects[0].faceIndex ];

var faceX = plane.geometry.vertices[ face.a ];

var faceY = plane.geometry.vertices[ face.b ];

var faceZ = plane.geometry.vertices[ face.c ];

var triangle = new THREE.Triangle ( faceX, faceY, faceZ );

var bary = triangle.barycoordFromPoint( raycastLast[0].point ) ;

Upon executing console.log( bary ), I receive

T…E.Vector3 {x: 11.585726082148518, y: 27.99652418990989, z: -38.58225027205841}
which appears incorrect as the values are unusually large.

I am seeking guidance on how to accurately obtain the barycentric coordinates from the intersection point within the scaled mesh triangle.

Appreciate your assistance.

Answer №1

After some experimentation, I finally grasped how to obtain the accurate values. Interestingly, the triangle UVs also required adjustment:

var faceX = new THREE.Vector3( plane.geometry.vertices[faceId.a].x / (1/scaleRatio) * scaleGeometryX, plane.geometry.vertices[faceId.a].y / (1/scaleRatio), 0);

var faceY = new THREE.Vector3( plane.geometry.vertices[faceId.b].x / (1/scaleRatio) * scaleGeometryX, plane.geometry.vertices[faceId.b].y / (1/scaleRatio), 0);

var faceZ = new THREE.Vector3( plane.geometry.vertices[faceId.c].x / (1/scaleRatio) * scaleGeometryX, plane.geometry.vertices[faceId.c].y / (1/scaleRatio), 0);

var triangle = new THREE.Triangle(faceX, faceY, faceZ);

var bary = triangleBar.barycoordFromPoint(intersects[0].point);

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

Obtaining the initial row information from jqGrid

If I use the getRowData method, I can retrieve the current cell content instead of the original data before it was formatted. Is there a way to access the original content before any formatting transformations are applied? Just so you know, I am filling t ...

What is the best way to populate a div with multiple other div elements?

My current project involves creating a sketchpad using jQuery for an Odin Project assignment. However, I have encountered an issue with filling the canvas (wrapper div) with pixels (pixel divs). The canvas does not populate correctly. Here is the link to m ...

What could be the reason for the appearance of this error message: 'Illegal arguments: undefined, string'?

Currently, I am in the process of developing a node.js application where I have created a backend API specifically for user registration. However, when testing it using Postman, I encountered an error message stating 'Illegal arguments: undefined, str ...

Leveraging the firebreath plugin to trigger a folder dialog, enabling asynchronous selection of folders to preserve the smooth execution of Java Script without any blocking

I need to ensure that only one folder selection dialog is open at any given time. Once the user picks a folder, an event will be triggered to notify the JavaScript of the selected folder. In order to open the dialog, I have integrated code from this gist ...

Not sure how to configure the settings for Firebase Firestore within the admin.firestore module

When trying to set an option at admin.firestore, I couldn't find the set method. It should be done like this: const settings = {timestampsInSnapshots: true} admin.firestore.settings(settings) However, I encountered a TypeError: Firestore.settings is ...

Is there a way to monitor the movement of an animated object in three js?

for (let ai = 0, al = gltf.animations.length; ai < al; ai++ ) { for (let ti = 0, tl = gltf.animations[ai].tracks.length; ti < tl; ti++ ) { let parts = gltf.animations[ai].tracks[ti].name.split('.'); // name is 'uu ...

Embed the component into the array collection

I have an array and I want to display a random component inside it. Specifically, I want to include the FeedbackComponent before the last two objects in the array. This is how it should look like in a schematic representation: storyObject storyObject st ...

Learn the art of animating "basic jQuery filtering" exclusively with CSS

Does anyone have suggestions on how to animate elements when filtered by JavaScript? The code I've tried so far doesn't seem to be working. Here's what I currently have: http://jsfiddle.net/ejkim2000/J7TF4/ $("#ourHolder").css("animation", ...

Discovering the process to create an onclick function with node.js code

index.html: <html> <h2>Welcome To User Profile Page !!!</h2> <button type="button">Edit Profile</button> <button type="button">Logout</button> </html> On my webpage, I have two buttons - Edit Profile and Lo ...

Concealing specific sections of HTML content in a webview on the fly

I've been experimenting with a proof of concept feature to implement the ability to conceal certain parts of a web page loaded in a webview, but I seem to be encountering some issues... Within a UIWebview extension, I have something similar to this c ...

Is it necessary for NPM to execute scripts labeled as dependencies during the npm i command execution?

When npm i is run, should it execute the scripts named dependencies? I've observed this behavior in the latest version of Node (v19.8.1) and I'm curious if it's a bug. To replicate this, follow these steps: mkdir test cd test npm init -y T ...

Executing an Ajax request that invokes a PHP function

After receiving valuable information in response to my previous inquiry through this link, I took the initiative to create a code that would notify me via email if it is discovered on another website. Below is the JavaScript code designed for potential co ...

Struggling with integrating Skybox in THREE.js

My console is not showing any errors. I am utilizing the live server VS code extension to execute the JS code. Can someone please assist me?" HTML: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

I am encountering TypeError issues while attempting to mock/test Vuex store modules

I'm currently in the process of learning how to effectively test components and JavaScript code, but I have hit a roadblock with Vuex modules. Below is the code snippet for the test: import { shallowMount } from '@vue/test-utils' import Wor ...

What would be the best way to create a JavaScript function that emulates the functionality of an Upgrade Button?

I am currently working on developing a clicker game and have reached the point where I need to implement a function for the 'upgrade click' button. This function should deduct a certain amount of money when clicked, while also increasing the amou ...

Understanding the behavior of the enter key in Angular and Material forms

When creating forms in my MEAN application, I include the following code: <form novalidate [formGroup]="thesisForm" enctype="multipart/form-data" (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$ev ...

The process of extracting text from an HTML element using Selenium and Node.js

After searching extensively on stackoverflow, I came up empty-handed in finding a solution to my problem. Can anyone lend a hand? I am trying to extract the text from an HTML element using the following code: var element = driver.findElement(webdriver.By ...

Utilizing the change function in conjunction with that

My attempt at creating a simple function to implement the change function didn't go as planned:/ What I am trying to achieve: 1- When a cost checkbox is checked, assign the corresponding cost (e.g., cost1.checked ? cost1 = 10 : 0) 2- Calculate and di ...

Issue with setting headers in Express.js when using an exported function

Exploring testing methods with Express using Mocha, Chai, Chai-HTTP plugin, and MongoDB with Mongoose. One particular test is designed to check if MongoDB correctly handles errors when attempting to retrieve a document with a faulty _id value (too short). ...

Handling Empty Body in Nest.js for Form Data

I am encountering an issue with a simple controller that I have. Within this controller, there is an endpoint defined as follows: @Post('/temp') async asdf( @Body() form: Record<string, string>, @Res({ passthrough: true }) response: Res ...