一条直线上离一个点最近的点通常可以通过画一条与该点相交的垂线来确定。
要找到垂直斜率,请执行以下代码:
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
这是斜率公式 (y2 - y1) / (x2 - x1)
现在我们有了坡度,很容易转换为垂直坡度。
var perpendicularSlope = -1 / slope;
现在,我们需要应用点斜率公式(y - y1 = 斜率 * (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)
接下来,我们要得到第一行的斜率截距形式。
var lineX = Number(a.substring(0, a.indexOf(","));
var lineY = Number(a.substring(a.indexOf(",") + 1, a.length));
var lineB = lineY - slope * newPointY;
我在这里创建了一个方程组。为了解决这个问题,我们必须使用传递性(如果 a = b 和 b = c,则 a = c);
var xCollision = (lineB - perpendicularBValue) / (perpendicularSlope - slope);
var yCollision = slope * xCollosion + lineB;
var d = xCollision + "," + yCollision;
我使用传递属性消除了 y 变量并将方程连接起来。然后我解决了x。然后我将 x 值插入并求解 y 值。这是原线和垂线相交的地方。
还记得我之前说过这通常有效吗?
由于您使用的是线 segments 而不是 lines,因此有时最近的点就是终点。
以下是固定 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;
我使用了一个称为距离公式((x1 - x2)^2 + (y1 - y2)^2 的平方根)的公式来确定点之间的距离。然后我使用速记 if 语句来确定最近点。
如果您需要更多帮助,请发表评论。