簡體   English   中英

html5畫布。 document.onkeypress箭頭鍵不起作用

[英]html5 canvas. document.onkeypress arrow keys not working

我正在嘗試創建一個簡單的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM