0

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?

1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.