html5画布。document.onkeypress箭头键不起作用

巴德伯格

我正在尝试创建一个简单的HTML5 Canvas足球游戏。游戏具有三个选项:玩家选择向左,向右或中间踢球,守门员是随机的,将向左,向右跳水或停留在中间。我希望用户按下向左,向右或向上箭头键来触发球员踢球,但是我无法让我的代码识别何时按下箭头键。我已经尝试了不同的键,这将工作,即返回键。

function canvasApp(){   

        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        //Other Var's

        document.onkeypress = function doKeyDown( e ) {
            var key = e.keyCode;
            if ( key == 37  ){
                userChoice = key;
            } else if (key == 38){
                userChoice = key;
            } else if (key == 39){
                userChoice = key;
            }
        }

        function draw() {
            ctx.clearRect( 0, 0, canvas.width, canvas.height );             
            //------------------------------------------------
            //Player shoots left
            if ( userChoice == 37 ){
                //More code
            //------------------------------------------------
            //Player shoots right
            } else if ( userChoice == 39 ){
                //More code
            //------------------------------------------------
            //Player shoots centre
            } else if ( userChoice == 38 ) {
                //More code
            }

            //------------------------------------------------
        }

        function gameLoop(){
            window.setTimeout(gameLoop, framerate);
            draw()
        }
        gameLoop();
    }

    document.onclick = function( e ){
        window.clearTimeout();
    }

如果您需要查看完整的代码,请告诉我,我将建立一个指向JSFiddle的链接。

杰伊·泽

您触发了错误的事件:请改用keydown:检查此页:http : //help.dottoro.com/ljlkwans.php

以下是jquery的代码段:如果您使用keypress事件,它将不起作用。

<html>
    <head>
        <title></title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    </head>
    <body>
    </body>
    <script type="text/javascript">
    $(document).ready(function(){

        $(document).keydown(function(e){
            var key = e.keyCode;
            if ( key == 37  ){
                console.log("left");
            } else if (key == 38){
                console.log("center");
            } else if (key == 39){
                console.log("right");
            }
        });
    });
    </script>
</html>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章