Javascript not getting keyDown input

Posted by William on Stack Overflow See other posts from Stack Overflow or by William
Published on 2010-06-13T19:49:35Z Indexed on 2010/06/13 19:52 UTC
Read the original article Hit count: 279

For some reason my code just isn't wanting to fire off any kind of OnKeyDown event. I don't know why. Can anyone tell me what I'm doing wrong?

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Canvas test</title>
        <meta charset="utf-8" />
        <link href="/bms/style.css" rel="stylesheet" />

        <style>
            body { text-align: center; background-color: #000000;}
            canvas{ background-color: #ffffff;}
        </style>

        <script type="text/javascript">
            var x = 50;
            var y = 250;
            var speed = 5;

            function controls(event){
                if(!e){
                  //for IE
                  e = window.event;
               }

               if(e.keyCode==37){//keyCode 37 is left arrow  
                  x -= speed;
               }

               if(e.keyCode==39){ //keyCode 39 is right arrow
                 x += speed;
               }

               if(e.keyCode==38){//keyCode 37 is up arrow  
                  y -= speed;
               }
               if(e.keyCode==40){ //keyCode 39 is down arrow
                 y += speed;
               }
            }

            function update(){
                document.onkeydown="controls(event);";
                draw();
            }

            function draw(){
              var canvas = document.getElementById('screen1');
              if (canvas.getContext){
                var ctx = canvas.getContext('2d');

                ctx.fillStyle = 'rgba(255,255,255,0.5)';
                ctx.fillRect(0,0,500,500);  
                ctx.fillStyle = 'rgb(236,138,68)';
                ctx.fillRect(x,y,25,25); 
                }
            }

            setInterval('update();', 1000/60);
        </script>

    </head>

    <body>
        <canvas id="screen1" width="500" height="500"></canvas> 
    </body>
</html>

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about usercontrols