-2

I have a Line(P1, P2) and a point NP(x,y), what I want is to create a parallel Line(A,B) pass through NP image I need a function in JavaScript for getting Line (A, B)

Solved: I write the function in JavaScript code with help of @MBo

function parallel(pt1, pt2, newPoint) {
 let NP = new THREE.Vector2(newPoint.x, newPoint.y)
 let p1 = new THREE.Vector2(pt1.x, pt1.y)
 let p2 = new THREE.Vector2(pt2.x, pt2.y)
 let dir = new THREE.Vector2(p2.x-p1.x, p2.y-p1.y);
 let W = new THREE.Vector2(NP.x-p1.x, NP.y-p1.y);
 let dw = dir.clone().dot(W);
 let dd = dir.clone().dot(dir);
 let dmw = dir.clone().multiplyScalar(dw).divideScalar(dd);
 let PP = p1.clone().add(dmw)
 let V = NP.clone().sub(PP)
 let pi1 = p1.add(V)
 let pi2 = p2.add(V)
 return {A:{x:pi1.x,y:pi1.y}, B:{x:pi2.x,y:pi2.y}}
}
  • Welcome to stackoverflow. We're not a code writing service, and all you've done is given a statement of intent, therefore implying we should do it for you. Do some research, give it a go, and if you're still struggling come back with a [mcve] of your code – freefaller Jul 19 '19 at 09:12
  • 1
    Hint: If you knew the slope of the line, how could that help you with your problem ? – collapsar Jul 19 '19 at 09:14
  • Since I cannot answer, I'll write it here. In the case where you don't need `A` and `B` to be as close as possible to `P1` and `P2`, simply use `A=NP`, and `B=P2+(NP-P1)`. It's parallel to `P1,P2`, and it goes through `NP`. – Gilles-Philippe Paillé Jul 19 '19 at 15:54

2 Answers2

3

Find projection of NP point onto P1P2 line.

enter image description here

At first get vectors

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

Point of projection of NP onto P1P2 using scalar(dot) prodict is:

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

and projection vector

V = NP - PP

Now ends of parallel segment are

P1' = P1 + V
P2' = P2 + V
MBo
  • 77,366
  • 5
  • 53
  • 86
1

Lets P1=[p1x,p1y], P2=[p2x,p2y], NP=[nx,ny] then

W = [wx,wy] = (P2-P1)/2 = [(p2x-p1x)/2, (p2y-p1y)/2]

and

A = NP-W = [nx-wx, ny-wy]
B = NP+W = [nx+wx, ny+wy]

JS code

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}]`);
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345