I am trying to implement an algorithm that will align a rectangle on an ellipse when a point is dragged.
The data I have is:
- I know what corner is being dragged
- the starting position of it
- the ending position of it
My old algorithm was to align the adjacent corners, but that only worked if the ellipse or rectangle weren't at an angle.
I am trying to implement something like Figma does:
My current idea is to take the sides that were changed on drag and match the other sides that weren't changed to the size of the changed sides. Though I'm not sure if that's correct.
CodePudding user response:
Let rectangle is described by center point (CX, CY)
and two unit direction vectors (WX, WY)
and (HX, HY)
, also W
is half-width, H
is half-height.
As far as I understand, rectangle slope is preserved, so direction vectors remain the same.
When corner number k
was shifted, it's new position is (NX, NY)
. Opposite vertex has number (k 2)%4
and it's position is (PX, PY)
(doesn't change)
New center is
CX' = (PX NX) / 2
CY' = (PY NY) / 2
New half-width and half-height
W' = 0.5 * Abs(WX * (NX - PX) WY * (NY - PY))
H' = 0.5 * Abs(HX * (NX - PX) HY * (NY - PY))