Robert Eisele
Engineer, Systems Architect and DBA

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}&\left(\begin{array}{c}x_1\\y_1\end{array}\right)+s\cdot\left(\begin{array}{c}a_1\\b_1\end{array}\right) = &\left(\begin{array}{c}x_2\\y_2\end{array}\right)+t\cdot\left(\begin{array}{c}a_2\\b_2\end{array}\right)\\\Leftrightarrow & s\cdot\left(\begin{array}{c}a_1\\b_1\end{array}\right)-t\cdot\left(\begin{array}{c}a_2\\b_2\end{array}\right)= & \left(\begin{array}{c}x_2\\y_2\end{array}\right)-\left(\begin{array}{c}x_1\\y_1\end{array}\right)\\\Leftrightarrow & \left(\begin{array}{cc}a_1 & -a_2\\b_1 & -b_2\end{array}\right)\cdot\left(\begin{array}{c}s\\t\end{array}\right)= & \left(\begin{array}{c}x_2-x_1\\y_2-y_1\end{array}\right)\\\Leftrightarrow & \left(\begin{array}{c}s\\t\end{array}\right)= & \left(\begin{array}{cc}a_1 & -a_2\\b_1 & -b_2\end{array}\right)^{-1}\cdot\left(\begin{array}{c}x_2-x_1\\y_2-y_1\end{array}\right)\\& = & \left(\begin{array}{cc}w_1 & -w_2\end{array}\right)^{-1}\cdot\left(\begin{array}{c}v_2-v_1\\\end{array}\right)\\& = & \frac{1}{a_2\cdot b_1 - a_1\cdot b_2}\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{(a_2-b_2) \cdot (x_2 - x_1) }{a_2\cdot b_1 - a_1\cdot b_2}\]

Plugging \(s'\) into the original equation of \(L_1\) gives us the desired point \(P\):

\[P = \vec{v_1}+s'\cdot\vec{w_1}\]

Or as a copy and paste solution:

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

   d = w2[0] * w1[1] - w1[0] * w2[1];

   if (d === 0)
      return null;

   s = (w2[0] - w2[1]) * (v2[0] - v1[0]) / d;
   return [
      v1[0] + s * w1[0],
      v1[1] + s * w1[1]

You might also be interested in the following


Sorry, comments are closed for this article. Contact me if you want to leave a note.