Created
October 29, 2017 08:06
-
-
Save Luftare/e28b82e5746c57ef15ea59fbef054725 to your computer and use it in GitHub Desktop.
Input class to capture keyboard and mouse events.
This file contains hidden or 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
class Input { | |
constructor(el = document) { | |
this.keys = []; | |
this.mouse = []; | |
this.mousemoveHandlers = []; | |
this.mousedownHandlers = []; | |
this.mouseupHandlers = []; | |
document.addEventListener("keydown", e => { | |
this.keys[e.key] = true; | |
}); | |
document.addEventListener("keyup", e => { | |
this.keys[e.key] = false; | |
}); | |
el.addEventListener("mousedown", e => { | |
e.preventDefault(); | |
this.mouse[e.which] = true; | |
this.mousedownHandlers.forEach(h => h(e)) | |
}); | |
el.addEventListener("mouseup", e => { | |
this.mouse[e.which] = false; | |
this.mouseupHandlers.forEach(h => h(e)) | |
}); | |
el.addEventListener("mouseleave", e => { | |
this.mouse = []; | |
}); | |
el.addEventListener("mousemove", e => { | |
this.mousemoveHandlers.forEach(h => h(e)) | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment