繁体   English   中英

canvas JavaScript中的按键检测

[英]Key detection in canvas javascript

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

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);

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

您确实在上面加上了括号,将其删除,实际的代码将是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM