Saturday, March 2, 2013

Keydown keyup example

Below is the code to test when a keydown and keyup code are triggered. The canvas shows a message when the left arrow key is pressed and then it is not pressed. 
You need to know when a key is pressed when a character is to be moved on the screen. Just copy and paste the code into a empty file and save it as a htm file. Then double click on it to see it in action. This code has been tested in ie9.

<!DOCTYPE = html>
<html><body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Use different browser.
</canvas>
<script>
 var c=document.getElementById("myCanvas");
 var ctx=c.getContext("2d");
 var test="Left arrow key is not pressed.";
 gameloop=setInterval(doGameLoop,16);
 window.addEventListener("keydown",kd,true);
 window.addEventListener("keyup",ku,true);
 function doGameLoop(){
  ctx.clearRect(0,0,c.width,c.height);
  ctx.fillText(test,10,10);
 }
 function kd(evt){
  if(evt.keyCode==37){
   test="Left arrow key is pressed.";
  }
 }
 function ku(evt){
  if(evt.keyCode==37){
   test="Left arrow key is not pressed.";
  }
 }
</script></body></html>

No comments:

Post a Comment