Lenght between a dot and a line //JavaScript Function
Given a dot and a line, it returns the distance between them, the last parameter tells if the line should be considered infinite or if the function should respect its limits.
[UPDATED CODE AND HELP CAN BE FOUND HERE]
1 2 //+ Jonas Raoni Soares Silva 3 //@ http://jsfromhell.com/math/dot-line-length [v1.0] 4 5 dotLineLength = function( x, y, x0, y0, x1, y1, o ){ 6 function lineLength( x, y, x0, y0 ){ 7 return Math.sqrt( ( x -= x0 ) * x + ( y -= y0 ) * y ); 8 } 9 if( o && !( o = function( x, y, x0, y0, x1, y1 ){ 10 if( !( x1 - x0 ) ) return { x: x0, y: y }; 11 else if( !( y1 - y0 ) ) return { x: x, y: y0 }; 12 var left, tg = -1 / ( ( y1 - y0 ) / ( x1 - x0 ) ); 13 return { x: left = ( x1 * ( x * tg - y + y0 ) + x0 * ( x * - tg + y - y1 ) ) / ( tg * ( x1 - x0 ) + y0 - y1 ), y: tg * left - tg * x + y }; 14 }( x, y, x0, y0, x1, y1 ), o.x >= Math.min( x0, x1 ) && o.x <= Math.max( x0, x1 ) && o.y >= Math.min( y0, y1 ) && o.y <= Math.max( y0, y1 ) ) ){ 15 var l1 = lineLength( x, y, x0, y0 ), l2 = lineLength( x, y, x1, y1 ); 16 return l1 > l2 ? l2 : l1; 17 } 18 else { 19 var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1; 20 return Math.abs( a * x + b * y + c ) / Math.sqrt( a * a + b * b ); 21 } 22 };