Skip to content

Instantly share code, notes, and snippets.

@Kzumueller
Last active March 5, 2020 12:04
Show Gist options
  • Save Kzumueller/1a85475dfc8b1cba31dfb05e0e23b76a to your computer and use it in GitHub Desktop.
Save Kzumueller/1a85475dfc8b1cba31dfb05e0e23b76a to your computer and use it in GitHub Desktop.
Calculating the angle for rotating an Element around its center
//module ...
/**
* rotates rotationTarget around its center point depending on the mouse position
* CTRL key must be pressed
*
* trigonometry powers, activate!
*
* @param event MouseEvent
*/
const mouseRotateListener = (event) => {
if(!event.ctrlKey) {
return;
}
const rect = rotationTarget.getBoundingClientRect();
const originX = rect.left + rect.width / 2;
const originY = rect.top + rect.height / 2;
const adjacent = event.clientX - originX;
const opposite = event.clientY - originY;
const hypotenuse = Math.sqrt(adjacent ** 2 + opposite ** 2);
let angle = Math.asin(opposite / hypotenuse);
if(adjacent < 0) {
angle = -(angle + Math.PI);
}
visualize(rotate(angle, []));
};
//module ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment