JS画几何图形之六【过直线外一点作垂线】

样例:http://www.zhaojz.com.cn/demo/draw10.html

依赖:【点】、【直线】

//过直线外一点画垂线
function drawVerticalLine(point, line){
//画辅助线-start
var color = 'DarkRed'; //垂线的颜色
var color2 = "#ccc"; //其它辅助线的颜色
drawPoint({
pw:2,ph:2,color:'DarkRed',point: line[0]
});
drawPoint({
pw:2,ph:2,color:'DarkRed',point: line[1]
});
drawLine(point, line[0], {color: color2});
drawLine(point, line[1], {color: color2});
//画辅助线-end drawPoint({
pw:2,ph:2,color:'DarkRed',point: point
}); var v_1_0 = line[1][1]-line[0][1];
var h_1_0 = line[1][0]-line[0][0];
var c_square = Math.pow(v_1_0,2) + Math.pow(h_1_0,2);
var c = Math.sqrt(c_square); //计算直线上两点之间的距离 var a_b_slope = 0;
var hasSlope = true;
if(v_1_0 == 0){
hasSlope = false;
}
a_b_slope = v_1_0/h_1_0; //直线的斜率 var point_pos = 1; //定义point与直线的位置关系
//当直线的斜率大于0时,如果点在直线上方,point_pos = 1,如果点在直线下方,point_pos = 3
//当直线的斜率小于0时,如果点在直线上方,point_pos = 2,如果点在直线下方,point_pos = 4
if(hasSlope){
var a_b_intercept = line[1][1]-a_b_slope*line[1][0];
var p_intercept = point[1]-a_b_slope*point[0];
if(a_b_slope >= 0){
if(p_intercept > a_b_intercept){
point_pos = 3;
}else{
point_pos = 1;
}
}else{
if(p_intercept < a_b_intercept){
point_pos = 2;
}else{
point_pos = 4;
}
}
}
//A为直线与水平线的夹角(锐角)
var sinA = Math.abs(v_1_0)/c; //sinA
var cosA = Math.abs(h_1_0)/c; //cosA
//C为垂线在顺时针方向上与水平线的夹角
var sinC = 0;
var cosC = 0;
//D为过point与line的平行线与水平线的夹角
var sinD = 0;
var cosD = 0;
switch(point_pos){
case 1:
sinC = cosA;
cosC = -sinA;
sinD = -cosC;
cosD = sinC;
break;
case 2:
sinC = cosA;
cosC = sinA;
sinD = cosC;
cosD = -sinC;
break;
case 3:
sinC = -cosA;
cosC = sinA;
sinD = cosC;
cosD = -sinC;
break;
case 4:
sinC = -cosA;
cosC = -sinA;
sinD = -cosC;
cosD = sinC;
break;
default:
}
//过point画line的平行线
drawLine(point, [point[0]+c*cosD, point[1]+c*sinD], {color: 'Red'});
drawLine(point, [point[0]+c*(-cosD), point[1]+c*(-sinD)], {color: 'Red'}); var point_v_1 = point[1]-line[1][1];
var point_h_1 = point[0]-line[1][0];
var point_dist_1 = Math.sqrt(Math.pow(point_v_1,2)+Math.pow(point_h_1,2)); //point到line上一点的距离
var point_v_0 = point[1]-line[0][1];
var point_h_0 = point[0]-line[0][0];
var point_dist_0 = Math.sqrt(Math.pow(point_v_0,2)+Math.pow(point_h_0,2)); //point到line上另外一点的距离
var s = (c+point_dist_1+point_dist_0)/2;
var area = Math.sqrt(s*(s-c)*(s-point_dist_0)*(s-point_dist_1)); //以point、line[0]和line[1]为顶点的三角形的面积
var h = 2*area/c; //三角形的高 var vpoint = [point[0]+h*cosC, point[1]+h*sinC]; //垂点
drawLine(point, vpoint); //画垂线
}
上一篇:GNU 项目(开源社区的由来,背后的哲学)


下一篇:jdk1.8 HashMap 实现 数组+链表/红黑树