计算垂直于直线的点

时间:2015-04-05 10:45:23

标签: java javascript

我在两个变量中有两个点存储,它形成一条线。我想从该行的一个端点找到一条与该直线垂直的点。

假设我有两个点P1(x1,y1)和P2(x2,y2)然后我想找到第三个点P3,使得线(P1-P2)垂直于线(P2,P3)并且在P2。

4 个答案:

答案 0 :(得分:2)

首先,角度:

public static double angle (double x1, double y1, double x2, double y2) {
    double xdiff = x1 - x2;
    double ydiff = y1 - y2;
    //double tan = xdiff / ydiff;
    double atan = Math.atan2(ydiff, xdiff);
    return atan;
}

要获得垂线,必须将PI / 2添加到由两点定义的线的角度。

一旦你有了这个角度,公式就是:

x = interceptPt.x + sin(perp_angle) * distance;
y = interceptPt.y + cos(perp_angle) * distance;

答案 1 :(得分:1)

如果您想使用Java,我建议您使用JTS。创建一个LineSegment并使用pointAlongOffset方法。给定点p1和p2,代码看起来像:

// create LineSegment
LineSegment ls = new LineSegment(p1.getX(), p1.getY(), p2.getX(), p2.getY());
// perpendicular distance to line
double offsetDistance = 10;
// calculate Point right to start point
Coordinate startRight = ls.pointAlongOffset(0, offsetDistance);
// calculate Point left to start point
Coordinate startLeft = ls.pointAlongOffset(0, -offsetDistance);
// calculate Point right to end point
Coordinate endRight = ls.pointAlongOffset(1, offsetDistance);
// calculate Point left to end point
Coordinate endLeft = ls.pointAlongOffset(1, -offsetDistance);

答案 2 :(得分:0)

我在http://jsfiddle.net/eLxcB/2/

得到了答案
// Start and end point
var startX = 120
var startY = 150
var endX = 180
var endY = 130
R.circle(startX,startY,2);

// Calculate how far above or below the control point should be
var centrePointX = startX
var centrePointY = startY;

// Calculate slopes and Y intersects
var lineSlope = (endY - startY) / (endX - startX);
var perpendicularSlope = -1 / lineSlope;
var yIntersect = centrePointY - (centrePointX * perpendicularSlope);

// Draw a line between the two original points
R.path('M '+startX+' '+startY+', L '+endX+' '+endY);

// Plot some test points to show the perpendicular line has been found
R.circle(100, (perpendicularSlope * 100) + yIntersect, 2);

答案 3 :(得分:0)

您可以将您的积分存储在vec2d中,然后使用一些数学公式来获得垂直点。

vec2d getPerpendicularPoint(vec2d A, vec2d B, float distance)
{
   vec2d M = (A + B) / 2;
   vec2d p = A - B;
   vec2d n = (-p.y, p.x);
   int norm_length = sqrt((n.x * n.x) + (n.y * n.y));
   n.x /= norm_length;
   n.y /= norm_length;
   return (M + (distance * n));
}