How to calculate the mirror point along a line?

前端 未结 8 1654
灰色年华
灰色年华 2020-12-31 18:09

In 2D plane, I have a point and a line. How to get the mirror point along this line?

8条回答
  •  独厮守ぢ
    2020-12-31 18:39

    I develop JS code which calculate formula from Ted Hop answer : Q' = Q + 2(I - nnT)(P - Q) transformed to

    Q' = Q + 2(I - d2vvT)(P - Q)

    Where column vector v=R-P is normal to line but not unit (like n) where P and R are two arbitrary line points; the vvT is outer product; the d=1/sqrt(vx*vx + vy*vy) is inverse length of v. Because we use d2 (=r in code) we can optimize calculations by omit sqrt

    // 2D Points P=[x,y] and R are points on line, 
    // Q is point for which we want to find reflection
    function mirror(Q,[P,R]) {
      let [vx,vy]= [ R[0]-P[0], R[1]-P[1] ];
      let [x,y]  = [ P[0]-Q[0], P[1]-Q[1] ];
      let r= 1/(vx*vx+vy*vy);
      return [ Q[0] +2*(x -x*vx*vx*r -y*vx*vy*r), 
               Q[1] +2*(y -y*vy*vy*r -x*vx*vy*r)  ];
    }
    
    console.log( mirror([3,2], [[2,4],[4,5]]) )

提交回复
热议问题