This question involves elementary school level algebra: There are only 3 options for the closest point:
- one of the points (x1,y1) (x2,y2)
- another point between them on the line segment
It's easy to find the distance between (x3,y3) to the two points using Pythagoras:
d1 = d(<x1,y1>,<x3,y3>) = sqrt( (x1-x3)^2 + (y1-y3)^2)
and
d2 = d(<x2,y2>,<x3,y3>) = sqrt( (x2-x3)^2 + (y2-y3)^2)
and now for the "more complicated" part: if there's another point on the segment which is closer to (x3,y3) - if we connect these points - we'll have a new segment that will be diagonal to the original segment - we have to use that together with a first degree equation (for a line) to find that third point and see if it's on the segment or outside (if it's outside of the segment then we'll take the minimum distance between (x3,y3) to the other two points.
The line equation (excuse my English - I learnt it in my native language so bear with me) is:
(I) y = mx + d
where m is easy to calculate:
m = (y1-y2)/(x1-x2)
and now that we know the value of m
in order to find d
we'll use the values of one of the first two points, for example:
y1 = mx1 +d => d = y1 - mx1
the diagonal line will have m'
which is -1/m
and if we'll use the values of (x3,y3) we'll find d'
. So now we know both the values of (I) as well as the equation for the diagonal line:
(II) y=m'x + d'
and if we'll use these two equations we can find the point on the line through which the original segment goes through which is the closest to (x3,y3) - if this point lies on the segment - we're done, otherwise, like earlier mentioned - we'll take the minimum between d1
and d2