画布javascript中的键检测

时间:2014-02-04 18:44:12

标签: javascript canvas keyboard

我尝试绘制一个简单的矩形并通过键盘移动它。但问题是我想在我的代码中添加了我需要的所有内容......我想在键盘上使用箭头。但在我尝试获取警报之前....但它不起作用.....请帮助我...任何帮助将不胜感激。

var canvas = document.getElementById("screen");
        context = canvas.getContext("2d");

function Player() {
        this.x=0, this.y = 0, this.w = 50, this.h = 50;
        this.render = function (){
            context.fillStyle = "orange";
            context.fillRect(this.x, this.y, this.w, this.h);
        }
      }                
      var player = new Player();

player.x=100;
            player.y= 460;
            setInterval( function() {
                context.fillStyle="black";
                context.fillRect(0,0,canvas.width, canvas.height);
                /*context.fillStyle = "white";
                context.fillRect(100, 460, 30 , 30);*/

                player.render();

                //move all aliens & draw all aliens
                for(var i = 0; i < 9; i++) {
                    aliens[i].move(),
                    aliens[i].draw(context);
                }
            }, 20);
            document.addEventListener('keydown', function(event)){
                var key_press = String.fromCharCode(event.keyCode);
                alert(event.keyCode + " | " + key_press);

            });
        }

1 个答案:

答案 0 :(得分:0)

document.addEventListener('keydown', function(event)){
----------------------------------------------------^

您确实在此处添加了额外的括号,将其删除,实际代码为

document.addEventListener('keydown', function(event){