# Calculate the intersection point of two Lines

Given two lines $$L_1$$ and $$L_2$$, how is it possible to calculate the point $$P$$ of intersection of these two objects? Like always, set the equations of the objects involved equal and solve for the parameters. For the two lines this means:

$L_1(s) = \vec{v_1}+s\cdot\vec{w_1}=\left(\begin{array}{c} x_1\\ y_1 \end{array}\right)+s\cdot\left(\begin{array}{c} a_1\\ b_1 \end{array}\right)$

$L_2(t) = \vec{v_2}+t\cdot\vec{w_2}=\left(\begin{array}{c} x_2\\ y_2 \end{array}\right)+t\cdot\left(\begin{array}{c} a_2\\ b_2 \end{array}\right)$

Setting the two equations equal yields:

$\begin{array}{rrl} & \vec{v_1}+s\cdot \vec{w_1} = & \vec{v_2}+t\cdot \vec{w_2}\\ \Leftrightarrow & s\cdot \vec{w_1}-t\cdot \vec{w_2}= & \vec{v_2}-\vec{v_1}\\ \Leftrightarrow & \left(\begin{array}{cc} \vec{w_1} & -\vec{w_2} \end{array}\right)\cdot\left(\begin{array}{c} s\\ t \end{array}\right)= & \vec{v_2}-\vec{v_1}\\ \Leftrightarrow & \left(\begin{array}{c} s\\ t \end{array}\right)= & \left(\begin{array}{cc} \vec{w_1} & -\vec{w_2} \end{array}\right)^{-1}\cdot\left(\begin{array}{c} \vec{v_2}-\vec{v_1}\\ \end{array}\right)\\ & = & \frac{1}{a_1\cdot b_2 - a_2\cdot b_1}\left(\begin{array}{cc} b_2 & -a_2\\ b_1 & -a_1 \end{array}\right)\cdot\left(\begin{array}{c} x_2-x_1\\ y_2-y_1 \end{array}\right)\\ \end{array}$

As $$L_1$$ with $$s$$ will lead to the same result as $$L_2$$ with $$t$$, we can decide for one:

$s' = \frac{b_2\cdot (x_2 - x_1) - a_2 \cdot (y_2 - y_1) }{a_1\cdot b_2 - a_2\cdot b_1}$

Plugging $$s'$$ into the original equation of $$L_1$$ gives us the desired point $$P$$:

$P =L_1(s') = \vec{v_1}+s'\cdot\vec{w_1}$

Or as a copy and paste solution:

var intersection = function(v1, w1, v2, w2) {

var det = w1 * w2 - w2 * w1;
if (det === 0) {
return null;
}
var s = (w2 * (v2 - v1) - w2 * (v2 - v1)) / det;
return [
v1 + s * w1,
v1 + s * w1];
};

You might also be interested in the following