Skip to content

Instantly share code, notes, and snippets.

@wklsh
Last active May 9, 2020 02:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wklsh/445eef5f20ca4f0ee9f7c2ee10d60c46 to your computer and use it in GitHub Desktop.
Save wklsh/445eef5f20ca4f0ee9f7c2ee10d60c46 to your computer and use it in GitHub Desktop.
Calculate Distance Between Mouse and center of Element
/**
* Calculate disance between mouse and center of element
* @param {obj} element target element
* @param {num} mouseX mouse pos X value
* @param {num} mouseY mouse pos Y value
*/
export function calcDistance(element, mouseX, mouseY) {
const elDimensions = element.getBoundingClientRect();
return Math.floor(
Math.sqrt(
Math.pow(mouseX - (elDimensions.left + elDimensions.width / 2), 2) +
Math.pow(mouseY - (elDimensions.top + elDimensions.height / 2), 2),
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment