I'm trying to rotate a point (element) relative to another point in 2D, but the element needs to be middle-centered, so I apply an elem.x = elem.x - elem.width / 2 transform before applying the rotation calculations.
The problem is that when rotating, this self-offset will make the position wobble at certain angles.
I repurposed a function from a library that applies the relative rotation, but I'm not that sharp on the trigonometry so I can't quite figure out where is it failing, or where/how to include this offset properly:
function updatePosition(pos) {
const rect = this.getClientRect();
pos.x = pos.x - rect.width / 2; // apply offset first
this.setAbsolutePosition(pos);
}
function rotateAroundPoint(deg, point) {
const rads = deg * (Math.PI / 180);
const rect = this.getClientRect(); // these functions are from a canvas library I'm using
const pos = this.getAbsolutePosition();
const x =
point.x
+ (pos.x - point.x) * Math.cos(rads)
- (pos.y - point.y) * Math.sin(rads);
const y =
point.y
+ (pos.x - point.x) * Math.sin(rads)
+ (pos.y - point.y) * Math.cos(rads);
this.rotation(rot);
this.setAbsolutePosition({ x, y });
}
These two get run in order when updating the rotation dynamically, the pos argument for the first one is simply the parent's center (the relative element).
This is how it looks:
(don't mind the width change)
