[算法]直线与圆的交点程序设计

时间:2022-08-30 10:00:59
/**
* Created by apple on 2017/1/15.
*/

//求直线与圆的交点
/*函数参数说明:
cx:圆X轴坐标
cy:圆y轴坐标
r:圆半径
stx:起点直线的X轴坐标
sty:起点直线的轴坐标
edx:终点直线的X轴坐标
edy:终点直线的Y轴坐标

返回值:交点坐标(x,y)
*/

function getPoint(cx,cy,r,stx,sty,edx,edy) {
// 求直线
var k = (edy - sty) / (edx - stx);
var b = edy - k*edx;
//列方程
var x1,y1,x2,y2;
var c = cx*cx + (b - cy)*(b- cy) -r*r;
var a = (1 + k*k);
var b1 = (2*cx - 2*k*(b - cy));

var tmp = Math.sqrt(b1*b1 - 4*a*c);
x1 = ( b1 + tmp )/(2*a);
y1 = k*x1 + b;
x2 = ( b1 - tmp)/(2*a);
y2 = k*x2 + b;
//判断求出的点是否在圆上
var res = (x1 -cx)*(x1 -cx) + (y1 - cy)*(y1 -cy);
var p = {};
if( res == r*r)
{

p.x = x1;
p.y = y1;
} else
{
p.x = x2;
p.y = y2;
}
return p;
}
//测试
var s = getPoint(10,20,50,34,45,12,34);
// 结果:{x: 48.2952871010182, y: 52.1476435505091}
console.log(s);