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

Check if square intersects line in JavaScript

给定正方形的位置和尺寸,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 (or another 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)