How to Read the Keyboard on JavaScript's Canvas for HTML5 and CSS3 Programming

The keyboard is a primary input technology for HTML5 programmers, especially for desktop machines. The standard way to read the keyboard in JavaScript's canvas is to set up special functions called event-handlers. JavaScript has a number of pre-defined event handlers you can implement. The keyDemo.html program illustrates a basic keyboard handler in action.

image0.jpg
<!DOCTYPE HTML>
<html lang="en-US">
<head>
 <meta charset="UTF-8">
 <title>keyDemo.html</title>
 <script type="text/javascript">
 //var keysDown = new Array(256);
 var output;
 function init(){
  output = document.getElementById("output");
  document.onkeydown = updateKeys;
 } // end init
 updateKeys = function(e){
  //set current key
  currentKey = e.keyCode;
  output.innerHTML = "current key: " + currentKey;
 }
 //keyboard constants simplify working with the keyboard
 K_A = 65; K_B = 66; K_C = 67; K_D = 68; K_E = 69; K_F = 70; K_G = 71;
 K_H = 72; K_I = 73; K_J = 74; K_K = 75; K_L = 76; K_M = 77; K_N = 78;
 K_O = 79; K_P = 80; K_Q = 81; K_R = 82; K_S = 83; K_T = 84; K_U = 85;
 K_V = 86; K_W = 87; K_X = 88; K_Y = 89; K_Z = 90;
 K_LEFT = 37; K_RIGHT = 39; K_UP = 38;K_DOWN = 40; K_SPACE = 32;
 K_ESC = 27; K_PGUP = 33; K_PGDOWN = 34; K_HOME = 36; K_END = 35;
 K_0 = 48; K_1 = 49; K_2 = 50; K_3 = 51; K_4 = 52; K_5 = 53;
 K_6 = 54; K_7 = 55; K_8 = 56; K_9 = 57;
 </script>
</head>
<body onload = "init()">
 <div id = "output">
  Press a key to see its code
 </div>
</body>
</html>

Managing basic keyboard input

This particular example demonstrates basic keyboard-checking as well as the more sophisticated technique used in simpleGame. Here's how the basic version works:

  1. Assigns a function to onkeydown.

    The document.onkeydown attribute is a special property. If you assign a function to this property, that function will be automatically called each time the operating system recognizes a key press. This example assigns the function updateKeys.

  2. Creates the function, including an event parameter.

    The updateKeys() function will automatically be given an event object (normally called e).

  3. Determines which key was pressed.

    The e.keyCode property returns a numeric code indicating which key was pressed. In the keyDemo program (as well as simpleGame), the currentKey variable holds this numeric value.

  4. Compares the key to one of the keyboard constants.

    It's hard to remember which keys are associated with which numeric values, so keyDemo and simpleGame provide a list of keyboard constants. They are easy to remember: K_A is the A key, and K_SPACE is the space bar. Of course, you can add other keys if there's some key you want to use that isn't available.

How to move an image with the keyboard

You can achieve a form of interactivity by having an image move in response to keyboard motion.

image1.jpg

Essentially moving an image involves combining key ideas from keyDemo.html (for keyboard input) and wrap.html (to set up the canvas and make the object move under timer control.) Here's the code:

<!DOCTYPE HTML>
<html lang = "en">
<head>
 <title>keyboard motion</title>
 <meta charset = "UTF-8" />
 <style type = "text/css">
 .hidden{
  display: none;
 }
 </style>
 <script type = "text/javascript">
 //move based on keyboard input
 var drawing;
 var con;
 var goofyPic;
 CANV_HEIGHT = 200;
 CANV_WIDTH = 200;
 SPR_HEIGHT = 50;
 SPR_WIDTH = 40;
 var x = 0;
 var y = 100;
 var dx = 0;
 var dy = 0;
 var currentKey;
 function init(){
 drawing = document.getElementById("drawing");
 con = drawing.getContext("2d");
 goofyPic = document.getElementById("goofyPic");
 document.onkeydown = updateKeys;
 setInterval(draw, 100);
 }
 function updateKeys(e){
 currentKey = e.keyCode;
 if (currentKey == K_LEFT){
  dx = -5;
 }
 if (currentKey == K_RIGHT){
  dx = 5;
 }
 if (currentKey == K_UP){
  dy = -5;
 }
 if (currentKey == K_DOWN){
  dy = 5;
 }
 if (currentKey == K_SPACE){
  dx = 0;
  dy = 0;
 }
 } // end updateKeys
 function draw(){
 //clear background
 con.clearRect(0, 0, 200, 200);
 currentKey = null;
 //move the element
 x += dx;
 y += dy;
 //check for boundaries
 wrap();
 //draw the image
 con.drawImage(goofyPic, x, y, SPR_WIDTH, SPR_HEIGHT);
 //draw a rectangle
 con.strokeStyle = "red";
 con.lineWidth = 5;
 con.strokeRect(0, 0, CANV_WIDTH, CANV_HEIGHT);
 } // end draw
 function wrap(){
 if (x > CANV_WIDTH){
  x = 0;
 }
 if (x < 0){
  x = CANV_WIDTH;
 }
 if (y > CANV_HEIGHT){
  y = 0;
 } // end if
 if (y < 0){
  y = CANV_HEIGHT;
 }
 } // end wrap
 //keyboard constants
 K_LEFT = 37; K_RIGHT = 39; K_UP = 38;K_DOWN = 40; K_SPACE = 32;
 </script>
</head>
<body onload = "init()">
 <h1>Keyboard Motion</h1>
 <img class = "hidden"
  id = "goofyPic"
  src = "andyGoofy.gif"
  alt = "Goofy pic of me" />
 <canvas id = "drawing"
   height = "200"
   width = "200">
 <p>Canvas not supported</p>
 </canvas>
 <p>
 Use arrow keys to move image, space bar to stop motion.
 </p>
</body>
</html>

This program is essentially wrap.html with the following changes:

  1. Sets up updateKeys() as an event handler.

    Because this program reads the keyboard in real time, you have to assign an event handler.

  2. Determines which key was pressed.

    Store the last key pressed in a variable called currentKey.

  3. Compares currentKey with keyboard constants.

    Use constants to compare currentKey with whatever keys you're interested in — for now, the arrow keys and space bar.

  4. Changes dx and dy based on the current key value.

    When you know which key is pressed, use this information to modify the dx and dy values, which determines how the image moves.

  5. The draw() function still does the drawing.

    The draw() function is called on a regular interval. It's common to separate input (keyPressed) from animation (draw).

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.