Course notes 25
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses

Keyboard Events

In the same method as listening, and reacting to, mouse events, key presses can also be monitored. Keyboard events are slightly more involved than Mouse events, as in addition to receiving the actual event, the key that was pressed must be determined.

The two standard events which monitor keyboard interaction are keydown and keyup. The first will fire when any key is pressed, and the second when any key is released.

To determine what key was pressed, the event properties charCode and keyCode can be checked. Due to browser inconsistences, it is always recommended to check both values. The easiest way to do this is with an if statement which assigns the value to a new variable. Since we are just checking values, and assignment is the goal, the best approach is to use a ternary operator to compress and simplify the if block. For review, the ternary syntax is:

condition ? true : false

Thus, the code inside the listener's callback function would be as follows:

var keyValue = e.charCode ? e.charCode : e.keyCode

in a full if statement the same code would look like:

if(e.charCode){
	var keyValue = e.charCode;
} else {
	var keyValue = e.keyCode;
}

The resulting variable will now contain the Unicode key code of the key pressed. For example, the Unicode key code of the Left Arrow Key is 37. If the actual textual name of the key is needed, the Unicode key code can be passed into String.fromCharCode(key code); to retrieve it. A reference to all the Unicode key codes can be found here.

The below example demonstrates how the keyboard can be used to control events on the canvas. Use the arrow keys to move the circle around on the surface. Note two lines.

1) The event listener is attached to the window. Since there is no way to attain a focus when checking the keyboard, you have to use the window to trigger the event.

2) The first line of each case within the updateCanvas function is important in that it stops the default behavior that would have normally occurred, given the event that was triggered. In this case, scrolling. If the content of this page extends beyond the window, the arrow keys will not work to scroll the page due to the inclusion of this line. Without it, the page would scroll AND the circle would move on the canvas. Keep this in mind when implementing key-based events.

var canvas, ctx, xPos,yPos;
function init(){
    canvas = document.getElementById('keycanvas');
    ctx = canvas.getContext('2d');
    
    window.addEventListener('keydown',updateCanvas,false);
    
    xPos = canvas.width/2;
    yPos = canvas.height/2;
    drawCanvas();
    
    
}

function updateCanvas(e){
    
    var keyValue = e.charCode ? e.charCode : e.keyCode;
    var delta = 5;
    switch(keyValue){
    
    case 37:	// left arrow
        e.preventDefault();
        if(xPos-30 >= 0) xPos-= delta;
        break;
    case 38:	// top arrow
        e.preventDefault();
        if(yPos-30 >= 0) yPos-= delta;
        break;
    case 39:	// right arrow
        e.preventDefault();
        if(xPos+30 <= canvas.width) xPos += delta;
        break;
    case 40:	// bottom arrow
        e.preventDefault();
        if(yPos+30 <= canvas.height) yPos += delta;
        break;
    
    }
    drawCanvas();
}

function drawCanvas() {
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.beginPath();
    ctx.arc(xPos,yPos,30,0,Math.PI*2,false);
    ctx.fill();
}