javascriptgeometryline-intersection

Check if square intersects line in JavaScript


Given the position and dimensions of a square, what is the equation in JavaScript for testing if a line goes through the rectangle?

What I have tried so far is:

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

This works for if the dimensions are:

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

But if the dimensions are like this, it won't work:

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

What is the correct formula for checking if a line segment intersects a square in JavaScript?


Solution

  • Use Cohen-Sutherland clipping algorithm (or another line clipping one)

    Get codes for both segments ends and check:

    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