Calculating the distance between a point and a line segment in Three.js

When working with Three.js, I have mastered a straightforward technique for determining the distance between a point (representing my camera's location) and an infinitely extending line. However, my current challenge lies in calculating the distance between a point and a specific line segment created by connecting two points. It is crucial to keep in mind that Three.js operates within the three spatial dimensions: x, y, and z.

Below is the formula I am currently utilizing to address the point to line segment distance calculation in Three.js:

var A = lineVertex1.clone()
var B = lineVertex2.clone()

var D = B.clone().sub( A ).normalize();
var d = camera.position.clone().sub( A ).dot( D );
var X = A.clone().add( D.clone().multiplyScalar( d ) );

var distance = camera.position.distanceTo( X );  

Answer №1

Approach 1 Using THREE.js

In order to calculate the distance between a point (A) and a line segment created by two other points (B and C), we can leverage the capabilities of THREE.Vector3. While it may not be a mesh, it serves as a geometric representation of a line.

The Vector3 class offers a convenient method called closestPointToPoint(), which allows us to determine the distance between point A and the line segment BC based on the result of this method.

const A = new Vector3(0, 0, 0);

const B = new Vector3(5, 2, 5); // coordinates of line endpoint 1
const C = new Vector3(5, -2, 5); // coordinates of line endpoint 2

const line = new Line3(B, C);
const distance = line.closestPointToPoint(A).distanceTo(A);

console.log(distance.toFixed(3)); // Output: 7.071 (which is equivalent to 5 × √2)

Approach 2 Employing Algebra


If we possess the coordinates of points A, B, and C, we can compute the distance between point A and the line BC using a mathematical formula provided at Math StackExchange.

Answer №2

While I may not be an expert at coding, I believe I can offer you the algorithm you need.

Consider extending a segment into an infinite line and then calculating the distance from the camera point to that line. The challenge lies in determining if the perpendicular drawn from the camera to the line falls within or outside the original segment. To solve this, compute three distances: from the camera to each end of the segment and from the camera to the line itself. The shortest of these distances should give you the desired result.

I hope this explanation proves useful to you.

Answer №3

The use of line.closestPointToPoint mentioned earlier is now considered outdated. For the updated method, refer to Line3.closestPointToPoint. The revised code snippet should be:

const pointA = new Vector3(0, 0, 0);

const pointB = new Vector3(5, 2, 5); // defining line base point 1
const pointC = new Vector3(5, -2, 5); // establishing line base point 2

const line = new Line3(pointB, pointC);
const targetPoint = new Vector3();

line.closestPointToPoint(pointA, false, targetPoint);
const distance = targetPoint.distanceTo(pointA);

console.log(distance.toFixed(3)); // Output: 7.071 (which equals 5 times the square root of 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

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

Manipulating video volume using JavaScript injection

My web page includes a video, and I have successfully used JavaScript injection to control the play/pause functionality. Now, I am looking to also adjust the volume based on percentage. How can I create a function that decreases or increases the volume acc ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...

utilizing a Bootstrap modal element throughout multiple HTML documents

I have a bootstrap modal dialog div that I want to use in all 4 html pages of my web application without repeating the code. I have a common JavaScript file for this purpose. What is the best way to achieve this? <!-- Modal --> <div class="modal ...

Customize your MUI Select to show the selected value in a different way within the Input field

I have a collection of objects and I am looking to link multiple attributes of the object in MenuItem, but I only want one attribute to be displayed in Select https://i.sstatic.net/kDKLr.png The image above displays "10-xyz" in the select display, when i ...

The art of deciphering a returned object in jQuery

Recently, I've been working with this jQuery code snippet: $.ajax({ type: "POST", url: "/problems/vote.php", dataType: "json", data: dataString, success: function ...

Submit a new HTML page and send a GET request to it following a POST request initiated from the initial page

As a newcomer to Node.js and JavaScript, I seek guidance on addressing a specific issue. My goal is to enable the client to submit a string to the server, which will then display the string data on a new HTML page. This setup utilizes Express and Socket.i ...

Execute JavaScript using Ajax technology

Although it has been discussed previously, my knowledge of javascript is quite limited, so I find myself a complete beginner. I am currently utilizing a javascript code that sends variables to a php file, and the information is then loaded into the current ...

Using JavaScript to open a window in ASPX page

When I use the code below to open a new window and receive a success message, I also want to close the current window. However, I am encountering an error: Error: newwindow is not defined var value = getQueryStrings(); var cust_id = value["cust_id ...

Discover a method to conceal an element within a <div> by monitoring mouseover events in a separate <div> container

<div id="one-id"> <div id="some">Information</div> <div id="control"> <div id="value-1"> <img id="image-one-id" /> <img id="image-two-id" /> ...

What could be the reason behind the improper display of JavaScript for ID overlay2?

Why is it that when I try to have two overlays with different messages display upon clicking buttons, they both end up showing the same message? Even after changing the ID tag names, the issue persists. Can someone shed some light on what might be causin ...

unable to detect image input type

My dilemma lies in trying to submit a form using an image input type. The ajax request works as expected, and I receive a response from my php script. However, I encountered an issue where the image button was not changing its image upon submission. Accord ...

Encountered an Ajax issue while initializing a datatable on a table inside a modal dialog

I have a modal that contains a search box. When the search button is clicked, an ajax call is made to the controller to retrieve a table of results, which are then inserted into a div like this: $.ajax({ url: url, data: JSON.stringify(viewModel), ...

Issue: Encounter of an unexpected token (Please ensure that plugins are installed to import files that are not JavaScript) while using the rollup vue package

I am working on creating a Vue component library, but I encountered an error with my type checking. I attempted to update TypeScript as mentioned here, but it did not resolve the issue. Here is a snippet of my code and `package.json` file. My component cod ...

What are the HTML5 elements that include the "load event" within their onload attribute?

Mozilla's MDN provides information regarding the load Event with this brief explanation: The load event is triggered when a resource and its dependent resources have completed loading. and references standard 1, which states Trusted Targets: ...

Looking for a way to upload only part of a large file using HTML and PHP

Is it possible to create a PHP script that can upload only the first 1 MB of a very large file? Can this be achieved with a standard form upload in PHP by closing off the connection after 1 MB is uploaded? I have researched various uploaders (HTML5/Java ...

The MessageError: expressjs is unable to read the property "image" because it is null

I am currently working on developing a shopping cart using express and mongodb. However, I encountered an error when attempting to include an image category in the form. Here is the code snippet for handling post requests in admin_product.js: router.post(& ...

Identify the corresponding IDs for each collection in the database

Within my database, I have several collections that are linked by their unique ID's to display relevant event(s). However, there is one specific collection that I am struggling to associate with the others. This collection is named events and each ev ...

I'm encountering some issues trying to install next-auth in my project built with Next.js and React

I recently set up my Next.js project with React using yarn create next-app. However, I am facing an issue as the next-auth package is not installed in my project. Currently, my node version is LTS 16.15.1, yarn version is 1.22.18, and npm version is 8.9. ...

How can I resolve the issue of the input field added dynamically by JavaScript not appearing in the PHP $_POST variable?

I have a form nested within an HTML table. Using jQuery, I am dynamically adding input fields to the form. However, when I submit the form and check the $_POST array with var_dump(), the added fields are not showing up. Why is this happening? Below is th ...