检查正方形在JavaScript中是否与线相交

时间:2018-12-24 01:15:00

标签: javascript geometry line-intersection

鉴于正方形的位置和尺寸,JavaScript中用于测试直线是否穿过矩形的等式是什么?

到目前为止,我尝试过的是:

function isSquareIntersectingLine(square, line) {
    return (
        line.startX >= square.topLeftX &&
        line.startX <= square.topLeftX + square.width &&
        line.endX >= square.topLeftX + square.width
    );
}

这适用于以下尺寸:

Square: {topLeftX: 0, topLeftY: 0, width: 5, height: 5}
Line: {startX: 2, startY: -4, endX: 6, endY: 3}

但是,如果尺寸是这样的,它将不起作用:

Square: {topLeftX: 0, topLeftY: 0, width: 5, height: 5}
Line: {startX: 2, startY: -4, endX: 3, endY: 10}

检查线段是否与JavaScript中的正方形相交的正确公式是什么?

1 个答案:

答案 0 :(得分:2)

使用Cohen-Sutherland clipping algorithm(或另一个line clipping

获取两个分段的代码并检查:

if both codes are zero, segment is inside (A-B case)
if code1 & code2 != 0 segment is outside  (K-L case)
if code1 & code2 = 0, analyze codes
    zero-nonzero: intersection exists (C-D)
    if code1 | code2 = 1100, 0011 : intersection exists (E-F)
         otherwise check for intersections with edges (GH)

enter image description here