Dealing With the Keyboard
With our triangle drawn, our next job is to deal with the keyboard. This involves the following steps:
- Listening for the events your keyboard fires
- Inside the event handler, accessing the
KeyboardEvent
'skeyCode
property.
Handling the cases when the left, right, up, and down arrow keys are pressed.
There are several ways of doing this, but we are going to use a familiar (but less-than-ideal approach). Go ahead and add the following lines of code just above where you defined your drawTriangle
function:
window.addEventListener("keydown", moveSomething, false);function moveSomething(e) {switch(e.keyCode) {case 37:// left key pressedbreak;case 38:// up key pressedbreak;case 39:// right key pressedbreak;case 40:// down key pressedbreak;}}
With the code we have just added, we first listen for a key press by listening for the keydown event. When that event gets overheard, we call the moveSomething
event handler that deals with each arrow key press. It does this dealing by matching the keyCode
property with the appropriate key value each arrow key is known by.