Created
September 10, 2016 19:54
-
-
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.
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
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