Minimum Distance between a Point and a Line
See here for a detailed explanation of this example and others.
The Equations
The equation:
P = P1 + u (P2 - P1)
Denotes how to find the point of where p3 would cross the line P1,P2.
u is worked out by the equation:
u = ((x3 - x1)(x2 - x1) + (y3 - y1)(y2 - y1)) / (||P2 - P1||^2)
This makes the two equations for the intersection:
x = x1 + u (x2 - x1) y = y1 + u (y2 - y1)
This makes working out the distance between P3 and the line (P1,P2) equal the same as working out the distance between P3 and (x,y).
Using the distance formula:
distance = sqrt((x2 - x1)^2 + (y2 - y1)^2)
Where x1 and y1 are the P3's x and y coordinates. And x2 and y2 are P's x and y coordinates.
Worked Example
Using the above equations and coordinates we get the following equations:
u = ((45 - 33)(100 - 33) + (100 - 10)(50 - 10)) / (||P2 - P1||^2)
u = 4404 / (||P2 - P1||^2)
u = 4404 / 6089.000000000001
u = 0.7232714731483001
This makes the position of P:
x = 33 + u (100 - 33) y = 10 + u (50 - 10) x = 81.4591887009361 y = 38.930858925932
Using these coordinates we can work out the distance between P3 and the line now:
distance = sqrt((81.4591887009361 - 45)^2 + (38.930858925932 - 100)^2)
distance = 71.12462606056278
Example JavaScript & HTML by Lyndon Armitage
Implementation of theory by Paul Bourke