算法 - 谈谈"求线段交点"的几种算法(js实现,完整版)
算法 - 谈谈"求线段交点"的几种算法(js实现,完整版)
已知两点的坐标,求直线的算法
已知两点坐标(x1,y1),(x2,y2)求过两点直线方程的算法.
1.斜截式
k=(y2-y1)/(x2-x1)
所以直线方程 y-y1=k(x-x1)
再把k代入
2.两点式
因为过(x1,y1),(x2,y2)
所以直线方程
(x-x1)/(x2-x1)=(y-y1)/(y2-y1)
求出两直线的解析式及图像的交点坐标:
l1与y轴相交于(0,1)与x轴相交在(4,0)
l2与y轴相交于(0,-3)与x轴相交在(-2,0)
设y1=kx+b
带入(0,1)(4,0)
得1=b
k=-1/4
则直线解析式为y1=-1/4x+1
同理y2=-设交点坐标为(a,b)
则b=-1/4a+1
b=-2/3a-3
的a=-48 b=13
∴交点坐标为(-48/5,17/5)
utils
// math
/**
* @method
* @notice 待完成
* @description 传入两天直线四个点,求交点
* @param {*} x1
* @param {*} y1
* @param {*} x2
* @param {*} y2
* @param {*} m1
* @param {*} n1
* @param {*} m2
* @param {*} n2
* @returns
*/
export function calcLinePoint(x1, y1, x2, y2, m1, n1, m2, n2) {
// let b = ((y2 - y1) / (x2 - x1)) * (a - x1) + y1;
// let b = ((n2 - n1) / (m2 - m1)) * (a - m1) + n1;
// ((y2 - y1) / (x2 - x1)) * (a - x1) + y1 = ((n2 - n1) / (m2 - m1)) * (a - m1) + n1
// a = (((n2 - n1) / (m2 - m1)) * (a - m1) + n1 - y1) / ((y2 - y1) / (x2 - x1)) + x1;
let x =
(((m1 * (n2 - n1) * (x2 - x1)) / (m2 - m1)) * (y2 - y1) +
(n1 * (x2 - x1)) / (y2 - y1) -
(y1 * (x2 - x1)) / (y2 - y1) +
x1) /
((((m2 - m1) * (y2 - y1) - (n2 - n1) * (x2 - x1)) / (m2 - m1)) * (y2 - y1));
let y = ((n2 - n1) / (m2 - m1)) * (x - m1) + n1;
// console.log([x, y]);
return [x, y];
}
// console.log(calcLinePoint(0, 80, 300, 0, 0, 0, 300, 80)); // [150,40]
// console.log(calcLinePoint(0, 1, 4, 0, 0, -3, -2, 0));
/**
* @method
* @description 输入直线上两点,求零一点的x或y
* @param {*} x1
* @param {*} y1
* @param {*} x2
* @param {*} y2
* @param {*} x
* @param {*} y
* @returns
*/
export function calcXY(x1, y1, x2, y2, x = null, y = null) {
if (y == null) y = ((y2 - y1) / (x2 - x1)) * (x - x1) + y1;
if (x == null) x = (y - y1) / ((y2 - y1) / (x2 - x1)) + x1;
return [x, y];
}
// console.log(calcXY(0, 80, 300, 0, 150, null));
// console.log(calcXY(0, 0, 300, 80, 150, null));
Lee2