Last active
March 5, 2020 12:04
-
-
Save Kzumueller/1a85475dfc8b1cba31dfb05e0e23b76a to your computer and use it in GitHub Desktop.
Calculating the angle for rotating an Element around its center
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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