在垂直于线段的线上找到与矩形相交的两个点

Finding two points that intersect a rectangle on a line that is perpendicular to a line segment

我遇到了以下问题:

鉴于:

找到点 D 和 E:

为了解决这个问题,我尝试先计算斜率并创建一个线函数,但是我看到的所有获得线和多边形交点的答案都使用线段而不是线功能。我该如何解决这个问题?我是否缺少一种更好的方法来找到不需要函数的垂直线?

function getPerpendicular(ax,ay,bx,by,cx,cy,x,y){
    let a=bx-ax;
    let b=by-ay;
    let slope;
    let line;
    // Because if a==0 the slope is infinite
    if(a===0){
        line=function(y){
            return cx;
        }
    }else{
        slope= (b)/(-a);
        line=function(x){
            return slope*x+cy-cx;
        }
    }
    // Intersection with the line function?
}

获取AB线的方向向量(你的a,b)

xx=bx-ax;
yy=by-ay;

获取垂直矢量

dx = - yy
dy = xx

现在垂线有参数方程(仅供参考,无需实现)

x = cx + dx * t
y = cy + dy * t

首先检查 horizontal/vertical 行

if dx = 0 then
    return cx, 0, cx, Y

if dy = 0 then
    return 0, cy, X, cy

先决条件:潜在的边界位置

if dx > 0 then
   bx1 = X
   bx2 = 0
else
   bx1 = 0
   bx2 = X

if dy > 0 then
   by1 = Y
   by2 = 0 
else
   by1 = 0
   by2 = Y

在一般情况下找到与水平和垂直边缘相交的参数

tx1 = (bx1 - cx) / dx
ty1 = (by1 - cy) / dy
tx2 = (bx2 - cx) / dx //should be negative
ty2 = (by2 - cy) / dy //should be negative

并为一端获取较小参数值的交集:

if tx1 <= ty1 then
   ix1 = bx1
   iy1 = cy + tx1 * dy
else
  iy1 = by1
  ix1 = cx + ty1 * dx

而对于另一端较大的参数值:

if tx2 >= ty2 then
   ix2 = bx2
   iy2 = cy + tx2 * dy
else
  iy2 = by2
  ix2 = cx + ty2 * dx

现在return两个交点

return ix1, iy1, ix2, iy2