We help IT Professionals succeed at work.

How do I calculate the projection of a point onto a line?

cvillegas asked
I need to know the equations to calculate projection of a point onto a line (at 90 degrees ~ right angle).

What's known:
Line (x0,y0) to (x1,y1)
Point (a,b)

Need the x and y equations of Point(a,b) projected (at right angle) onto Line (x0,y0) to (x1,y1)

Please heeeeeeelp! :(

PS: i'm willing to pay a max of 1000 points
Watch Question

  int main( int argc, int* argv ) {

    return argc;
Here's the answer.  If you need any further explanation let me know.  Most of the answer is just explanation of how to get the various values.  The real meat is down at the end.

Line 1 is the line defined by the two given points
Line 2 is the line defined by the one point and the unknown intersection of the two

What we know:

(x1, y1), (x2, y2)  The coordinates of the two points that define the line.
(a, b)              The coordinates of the point given

What we can easily calculate
m1 - the slope of Line 1
m1 = (y1 - y2) / (x1 - x2)

m2 - the slope of Line 2
m2 = -1 / m1

what we can calculate with a bit more effort
b1 - the Y intercept of Line 1.  Found by substituting x1 and y1 in the slope / intercept equation
first we need to solve the y = mx + b equation for b so:
b = y - mx
b1 = y1 - m1(x1)

and do the same for Line 2:
b2 = b - m2(a)

So now we can create two equations in the form y = mx + b, one for each line using the known values:

y = m1(x) + b1
y = m2(x) + b2

Substitue the first equation of y for y in the second we get:
m1(x) + b1 = m2(x) + b2

We can solve for x since everything else is a constant:
m1(x) - m2(x) = b2 - b1
(m1 - m2)(x) = b2 - b1

and finally:

x = (b2 - b1) / (m1 - m2)

Since b2, b1, m1, and m2 are all constants x is now known.

Take x and plug it back into one of the other equations and you have y:


How can I arrange to pay you the other 700  pts? Thank you VERY much for your clear explenation


There are two special cases that you have to deal with.  One is when your line has a slope of 0 (horizontal) and when the slope is infinity (vertical).  The solutions are trivial but if you try to do the calculations you will have problems.

For a horizontal line, the solution will be the x coordinate from the point and the y coordinate from either of the points on the line.

For a vertical line, the solution with be the x coordinate from either point on the line and the y coordinate from the point.