Skip to content

Instantly share code, notes, and snippets.

@rvighne
Created September 10, 2016 19:54
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 rvighne/07897dff43860558e52405cabb358b05 to your computer and use it in GitHub Desktop.
Save rvighne/07897dff43860558e52405cabb358b05 to your computer and use it in GitHub Desktop.
Returns an object whose keys are keyboard key names and whose values are booleans indicating whether the key is pressed or not.
function watchKeys(target = document) {
const watcher = {};
target.addEventListener('keydown', function (e) {
watcher[e.key] = true;
});
target.addEventListener('keyup', function (e) {
watcher[e.key] = false;
});
return watcher;
}
// EXAMPLE:
const watcher = watchKeys();
const player = {
x: 0,
y: 0
};
const ctx = document.createElement('canvas').getContext('2d');
document.body.appendChild(ctx.canvas);
setInterval(function () {
if (watcher.ArrowLeft) {
player.x--;
} else if (watcher.ArrowRight) {
player.x++;
}
if (watcher.ArrowUp) {
player.y--;
} else if (watcher.ArrowDown) {
player.y++;
}
ctx.fillRect(player.x, player.y, 1, 1);
}, 1000 / 30);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment