The closest point on a line to a point can usually be determined by drawing a perpendicular line intersecting the point.
To find the perpendicular slope, do the following code:
var slope = (Number(a.substring(a.indexOf(",") + 1, a.length)) //The Y coordinate of A
- Number(b.substring(b.indexOf(",") + 1, b.length))) // The Y coordinate of B
/ (Number(a.substring(0, a.indexOf(","))) // The X coordinate of A
- Number(b.substring(0, b.indexOf(",")))); //The Y coordinate of B
This is the slope formula (y2 - y1) / (x2 - x1)
Now that we have the slope, it is easy to convert to a perpendicular slope.
var perpendicularSlope = -1 / slope;
Now, we need to apply the point-slope formula (y - y1 = slope * (x - x1)).
var newPointX = Number(c.substring(0, c.indexOf(",")); //Gets the X value of new point
var newPointY = Number(c.substring(c.indexOf(",") + 1, c.length)); //Gets the Y value of new point
//Note that in the formula provided above, y and x are not going to be assigned in code.
//I'm going to bypass formatting it like that and go right to the slope intercept form
var perpendicularBValue = newPointY - perpendicularSlope * newPointX;
//Slope intercept form is y = mx + b. (m is slope and b is where the line intersects the y axis)
Next, we have to get the slope intercept form of the first line.
var lineX = Number(a.substring(0, a.indexOf(","));
var lineY = Number(a.substring(a.indexOf(",") + 1, a.length));
var lineB = lineY - slope * newPointY;
I've created a system of equations here. To solve it, we'll have to use the transitive property (if a = b and b = c, then a = c);
var xCollision = (lineB - perpendicularBValue) / (perpendicularSlope - slope);
var yCollision = slope * xCollosion + lineB;
var d = xCollision + "," + yCollision;
I eliminated the y variables using the transitive property and conjoined the equations. Then I solved for x. I then plugged the x value in and solved for the y value. This is where the original line and the perpendicular line meet.
Remember how earlier I stated that this usually works?
Since you're using line segments not lines, sometimes the closest point will be the end points.
Here's how to fix the value of d
var aDistance = Math.sqrt(
Math.pow(lineX - newPointX, 2) +
Math.pow(lineY - newPointY, 2));
var bDistance = Math.sqrt(
Math.pow(Number(b.substring(0, b.indexOf(",")) - newPointX, 2) +
Math.pow(Number(b.substring(b.indexOf(",") + 1, b.length) - newPointY, 2));
var dDistance = Math.sqrt(
Math.pow(xCollision - newPointX, 2) +
Math.pow(yCollision - newPointY, 2));
var closestEndpoint = aDistance < bDistance ? aDistance : bDistance;
var closestPoint = closestEndpoint < dDistance ? closestEndpoint : dDistance;
I used a formula called the distance formula (square root of (x1 - x2)^2 + (y1 - y2)^2) to determine the distance between the points. I then used shorthand if statements to determine the closest point.
If you need more help, just leave a comment.