过一点的平行线[闭合]

问题描述 投票:0回答:2

我有一条由两个点

P1
P2
以及一个点
NP
定义的线段。我想创建一条穿过
NP
的平行线。我正在使用 JavaScript 并寻找一个函数来计算平行线上点
A
B
的坐标。有人可以为此任务提供 JavaScript 函数,或者对我现有的代码提出改进建议吗?

image

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);
javascript geometry
2个回答
3
投票

找到 NP 点在 P1P2 线上的投影。

首先得到向量

Dir = (P2.X-P1.X, P2.Y-P1.Y)
W =   (NP.X-P1.X, NP.Y-P1.Y)

使用标量(点)积将NP投影到P1P2的点是:

PP = P1 + Dir * (Dir.dot.W) / (Dir.dot.Dir)

和投影向量

V = NP - PP

现在平行线段的末端是

P1' = P1 + V
P2' = P2 + V

1
投票

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}]`);

© www.soinside.com 2019 - 2024. All rights reserved.