Created
August 29, 2019 15:45
Star
You must be signed in to star a gist
Get element relative mouse position
This file contains 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
// 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