Contents
raw book

Let each line be defined by two points \(A_k\) and \(B_k\). The vector from \(A_k\) to \(B_k\) is \(\mathbf{v}_k\). We can then express each line parametrically with

\[L_1(t) = A_1 + \mathbf{v}_1t\\L_2(s)=A_2+\mathbf{v}_2s\]

The intersection occurs when \(L_1(t) = L_2(s)\), or

\[A_1 + \mathbf{v}_1t = A_2+\mathbf{v}_2s\]

Subtracting \(A_1\) from both sides and perping with \(\mathbf{v}_2\) yields

\[(\mathbf{v}_1\perp\mathbf{v}_2) t = (A_2- A_1)\perp\mathbf{v}_2\]

Dividing by \(\mathbf{v}_1\perp\mathbf{v}_2\) yields

\[t = \frac{(A_2- A_1)\perp\mathbf{v}_2}{\mathbf{v}_1\perp\mathbf{v}_2}\]

and symmetrically

\[s = \frac{(A_2- A_1)\perp\mathbf{v}_1}{\mathbf{v}_1\perp\mathbf{v}_2}\]

JavaScript Implementation

function LineLine(A1, B1, A2, B2) {

    const v0 = Vector2.fromPoints(A1, A2);
    const v1 = Vector2.fromPoints(A1, B1);
    const v2 = Vector2.fromPoints(A2, B2);

    const w = v1.cross(v2);

    if (w !== 0) {

        const t = v0.cross(v2) / w;
        const s = v0.cross(v1) / w;

        if (t <= 1 && s <= 1 && 0 <= t && 0 <= s) {
            return v1.scale(t).add(A1);
        }
    }
    return null;
}