javascriptmathgeometry

Finding the projection of a point onto a line


I am not very good at math and I am aware that there are other people asking similar things to me but I don't really understand the explanations.

My problem is: I have a line given by 2 points A,B and another point C, I would like to find a point on the line AB that represents the projection of the point C on the line AB.

For example lets say I have the coordinates for A and B and for the point C, I would like to find the coordinate for D as per the figure below:

A---D-------------B
         
    C

Solution

  • Make vectors:

    AB = B - A
    AC = C - A
    

    Or in coordinates:

    AB = (abx, aby)
    AC = (acx, acy)
    

    Where:

    abx = B.x - A.x
    aby = B.y - A.y
    acx = C.x - A.x
    acy = C.y - A.y
    

    The simplest form of projection of C onto A—B, using the dot product, is:

    AD = AB * (AB dot AC) / (AB dot AB)
    D = (dx, dy) = A + AD
    

    Or in coordinates:

    coeff = (abx*acx + aby*acy) / (abx*abx+aby*aby)
    dx = A.x + abx * coeff
    dy = A.y + aby * coeff