HTML Keyboard game code example

Example: wasd controls javascript

function MyKeyUpHandler (MyEvent) { 
   if (MyEvent.keyCode == 65 || MyEvent.keyCode == 68) {hero.velocity_x= 0}; // not left or right
   if (MyEvent.keyCode == 87 || MyEvent.keyCode == 83) {hero.velocity_y= 0}; // not up or down
   }


function MyKeyDownHandler (MyEvent) { 
   if (MyEvent.keyCode == 65) {hero.velocity_x=  -Quickness};  // left
   if (MyEvent.keyCode == 87) {hero.velocity_y=  -Quickness};  // up
   if (MyEvent.keyCode == 68) {hero.velocity_x=   Quickness};  // right
   if (MyEvent.keyCode == 83) {hero.velocity_y=   Quickness};  // down
   MyEvent.preventDefault();
   }
function MyTouchHandler (MyEvent) { 
   var rect = myCanvas.getBoundingClientRect();           // where is our canvas
   hero.velocity_y= 0; 
   hero.velocity_x= 0;                                    // zero out velocity

   for (var i=0; i < MyEvent.touches.length; i++) {
       var x = MyEvent.touches[i].clientX - rect.left;    // get x & y coords
       var y = MyEvent.touches[i].clientY - rect.top;     // relative to canvas

       // Add velocity depending on which thirds we see touch

       if (x > myCanvas.width * 0.66) hero.velocity_x= hero.velocity_x + Quickness;  
       if (x < myCanvas.width * 0.33) hero.velocity_x= hero.velocity_x - Quickness;  
       if (y > myCanvas.height * 0.66) hero.velocity_y= hero.velocity_y + Quickness; 
       if (y < myCanvas.height * 0.33) hero.velocity_y= hero.velocity_y - Quickness; 
       }

   MyEvent.preventDefault();   
   }