Skip to content

Instantly share code, notes, and snippets.

@greggman
Created August 29, 2019 15:45
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save greggman/c28bfbe50f6a27e53626a6860cf168a3 to your computer and use it in GitHub Desktop.
Get element relative mouse position
// use clientX, clientY
someElement.addEventListener('mousemove', (e) => {
const rect = someElement.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
}
// the problem with clientX, clientY is they don't work with CSS transforms.
// use offsetX, offsetY. Note the event must be attached to the element
// as offsetX and offsetY must be relative to some element
someElement.addEventListener('mousemove', (e) => {
const x = e.offsetX; // relative to someElement
const y = e.offsetY; // relative to someElement
});
// the good part of offsetX and offsetY is they work with CSS transforms
// the bad part is they only work with the mouse, not touch events
// the workaround is to dispatch our own events
window.addEventListener('mousemove', resendEvent);
window.addEventListener('touchmove', (e) => {
for (let i = 0; i < e.touches.length; ++i) {
resendEvent(e.touches[i]);
}
});
function resendEvent(e) {
someElemment.dispatchEvent(new MouseEvent('mousemove', {
clientX: e.clientX,
clientY: e.clientY,
});
}
someElement.addEventListener('mousemove', (e) => {
const x = e.offsetX; // relative to someElement
const y = e.offsetY; // relative to someElement
});
// for canvas relative values we need to take into account
// the canvas might have more or less pixels than are actually displayed
function convertToCanvasRelativePosition(elementRelativeX, elementRelativeY) {
return {
x: elementRelativeX * canvas.width / canvas.clientWidth,
y: elementRelativeY * canvas.height / canvas.clientHeight,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment