已知直線上兩點爲:(x1,x2),(y1,y2);spa
設方程爲:Ax+By+C=0;code
1. 求斜率:k=(y2-y1)/(x2-x1);blog
2. 直線方程爲: y-y1=k(x-x1);get
換算得:kx-y+y1-kx1=0,即:io
A=k B=-1 C=y1-kx1=y1-(y2-y1)/(x2-x1)*x1
1. 點(x0,y0)到直線的距離公式爲:function
d=abs(Ax0+By0+C)/sqrt(A*A+B*B);
2. 設垂足爲p,則:class
p.x=(B*B*x0-A*B*y0-A*C)/(A*A+B*B)
p.y=(A*A*y0-A*B*x0-B*C)/(A*A+B*B)
輸入點和線段,返回距離和垂足di
1 function getDistanceP2L(point,line){ 2 3 var x1=line.startPoint.x; 4 var y1=line.startPoint.y; 5 var x2=line.endPoint.x; 6 var y2=line.endPoint.y; 7 var x0=point.x; 8 var y0=point.y; 9 10 var k=x1==x2?10000:(y2-y1)/(x2-x1);//當x1=x2時,給斜率設一個較大值10000 11 var a=k; 12 var b=-1; 13 var c=y1-k*x1; 14 15 var d=Math.abs(a*x0+b*y0+c)/Math.sqrt(a*a+b*b); 16 17 var px=(b*b*x0-a*b*y0-a*c)/(a*a+b*b); 18 var py=(a*a*y0-a*b*x0-b*c)/(a*a+b*b); 19 var p=new Point(px,py); 20 21 return [d,p]; 22 }