Skip to content

Instantly share code, notes, and snippets.

@trustedtomato
Last active October 22, 2017 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trustedtomato/42ca64e14986d9a605e8b6a86b81d231 to your computer and use it in GitHub Desktop.
Save trustedtomato/42ca64e14986d9a605e8b6a86b81d231 to your computer and use it in GitHub Desktop.
Tracking cursor position & improved mousemove event
const cursor = (() => {
const cursorEventTarget = Object.assign(document.createDocumentFragment(), {x: 0, y: 0});
let changed = false;
const onmove = (e:MouseEvent) => {
if(cursorEventTarget.x !== e.x || cursorEventTarget.y !== e.y){
cursorEventTarget.x = e.x;
cursorEventTarget.y = e.y;
changed = true;
}
};
const ondown = (e:MouseEvent) => {
cursorEventTarget.dispatchEvent(new MouseEvent('down', e));
onmove(e);
};
const onup = (e:MouseEvent) => {
cursorEventTarget.dispatchEvent(new MouseEvent('up', e));
};
(function loop(){
if(changed){
changed = false;
cursorEventTarget.dispatchEvent(new Event('move'));
}
requestAnimationFrame(loop);
})();
document.addEventListener('mousedown', ondown);
document.addEventListener('mouseup', onup);
document.addEventListener('mousemove', onmove);
return cursorEventTarget;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment