给定正方形的位置和尺寸,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中的正方形相交的正确公式是什么?

最佳答案

使用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)


javascript - 检查正方形是否与JavaScript中的线相交-LMLPHP

关于javascript - 检查正方形是否与JavaScript中的线相交,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53908349/

10-14 18:55
查看更多