我有一条由两个点
P1
和 P2
以及一个点 NP
定义的线段。我想创建一条穿过NP
的平行线。我正在使用 JavaScript 并寻找一个函数来计算平行线上点 A
和 B
的坐标。有人可以为此任务提供 JavaScript 函数,或者对我现有的代码提出改进建议吗?
function createParallelLine(P1, P2, NP) {
// Calculate the direction vector of the original line segment
const directionVector = {
x: P2.x - P1.x,
y: P2.y - P1.y
};
// Normalize the direction vector
const length = Math.sqrt(directionVector.x ** 2 + directionVector.y ** 2);
const normalizedDirection = {
x: directionVector.x / length,
y: directionVector.y / length
};
// Calculate the perpendicular vector
const perpendicularVector = {
x: -normalizedDirection.y,
y: normalizedDirection.x
};
// Calculate the new points A and B for the parallel line
const A = {
x: NP.x + perpendicularVector.x,
y: NP.y + perpendicularVector.y
};
const B = {
x: NP.x - perpendicularVector.x,
y: NP.y - perpendicularVector.y
};
return { A, B };
}
// Example usage:
const P1 = { x: 1, y: 1 };
const P2 = { x: 4, y: 4 };
const NP = { x: 2, y: 2 };
const { A, B } = createParallelLine(P1, P2, NP);
console.log("Point A:", A);
console.log("Point B:", B);
让
P1=[p1x,p1y]
,P2=[p2x,p2y]
,NP=[nx,ny]
然后
W = [wx,wy] = (P2-P1)/2 = [(p2x-p1x)/2, (p2y-p1y)/2]
和
A = NP-W = [nx-wx, ny-wy]
B = NP+W = [nx+wx, ny+wy]
JS代码
function parallel([p1x,p1y],[p2x,p2y],[nx,ny]) {
let wx = (p2x-p1x)/2;
let wy = (p2y-p1y)/2;
return [[nx-wx,ny-wy],[nx+wx,ny+wy]]
}
// TEST
let P1 = [2,3];
let P2 = [6,5];
let NP = [5,2];
let [A,B] = parallel(P1,P2,NP);
// print
console.log(`for P1=[${P1}], P2=[${P2}], NP=[${NP}]
result is A=[${A}], B=[${B}]`);