Skip to content

Instantly share code, notes, and snippets.

@kayac-chang
Created September 13, 2020 08:21
Show Gist options
  • Save kayac-chang/861f6be2970f47eaccc6b0814a930ccf to your computer and use it in GitHub Desktop.
Save kayac-chang/861f6be2970f47eaccc6b0814a930ccf to your computer and use it in GitHub Desktop.
sync keyboard event to requestAnimationFrame
export function KeyBoard(keymap) {
const pressing = new Set();
window.addEventListener("keydown", ({ key }) =>
keymap[key] && pressing.add(keymap[key])
);
window.addEventListener("keyup", ({ key }) =>
keymap[key] && pressing.delete(keymap[key])
);
return () => pressing;
}
import { KeyBoard } from './KeyBoard';
const getAction = KeyBoard({
w: 'Up',
s: 'Down',
a: 'Left',
d: 'Right',
});
function loop() {
// get current press key
const pressing = getAction();
// print out the key you press
console.log(pressing);
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment