Last active
October 22, 2017 18:26
-
-
Save trustedtomato/42ca64e14986d9a605e8b6a86b81d231 to your computer and use it in GitHub Desktop.
Tracking cursor position & improved mousemove event
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
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