Skip to content

Instantly share code, notes, and snippets.

@christopherkade
Created August 18, 2019 16:34
Show Gist options
  • Save christopherkade/709ba844f6d5072832abfbabd32274ca to your computer and use it in GitHub Desktop.
Save christopherkade/709ba844f6d5072832abfbabd32274ca to your computer and use it in GitHub Desktop.
Calculating an angle based on mouse movement
/**
* Calculates the angle based on the user's mouse position and a given point
* @param {*} x1 - Mouse X pos
* @param {*} y1 - Mouse Y pos
*/
const getAngle = (x1, y1, x2, y2) => {
var distY = Math.abs(y2 - y1);
var distX = Math.abs(x2 - x1);
// Calculate the hypotenuse
var dist = Math.sqrt((distY * distY) + (distX * distX));
var val = distY / dist;
// Return angle in degrees
return Math.degrees(Math.asin(val));
}
document.addEventListener('mousemove', ({ clientX, clientY }) => {
getAngle(clientX, clientY, 500, 0)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment