Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm making game in JavaScript. I have canvas for drawings and game loop. I'd like to make method readKeyboard, in game loop, to check if there is any pressed key. I don't want to attach event to canvas, because it doesn't fit game loop design. Maybe I should attach this event? What is the best solution?

share|improve this question
up vote 5 down vote accepted

You could use a library like KeyboardJS, which will listen the keyboard events and fill an array with the active keys.

In your gameloop:

var activeKeys = KeyboardJS.activeKeys();
if (activeKeys.indexOf(84) > -1) {
  // key pressed

I also made my own library, which is lighter but clearly less complete than KeyboardJS.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.