Calculate distance between two rotated elements

Viewed 241

Hi I want to calculate the perpendicular distance between two rotated elements, when rotation is 0 I use el1.getBoundingClientRect().x - el2.getBoundingClientRect().x and it gives me right distance, but for rotated elements, it does not work as it gives the perpendicular distance between the vertexes (the distance of bounding rectangles, how can I get x? thanks! Ex. one what I am looking for

The result when elements are roteted

https://codesandbox.io/s/epic-thunder-mxqbc?file=/src/index.js

1 Answers

If differences of vertex coordinates of two rectangles before rotation were (dx, dy), then after rotattion by angle fi new differences are:

 nx = dx * cos(fi) - dy * sin(fi)
 ny = dx * sin(fi) + dy * cos(fi)

If we multiply the first equation by cos(fi) and the second one by sin(fi), then add them, we can find needed value

dx = nx * cos(fi) + ny * sin(fi)

(assuming you know vertex difference in rotated state)

For example below: dx was 25, cos(fi)=4/5, sin(fi)=3/5
After rotation: nx = 5, ny = 35, we can find dx = 5*4/5 + 25*3/5 = 4+21 = 25

enter image description here enter image description here

Related