Javascript document.addEventListener仅适用于1个密钥代码

时间:2015-11-17 20:23:40

标签: javascript

我有一个简单的程序,这只是一个片段。

window.onload = function() {
    var canvas = document.getElementById("paper");

    var player = canvas.getContext("2d");
    var background = canvas.getContext("2d");
    var platform = canvas.getContext("2d");

    var backgroundColor = "rgb(140, 75, 2)";

    var platformColor = "rgb(60, 20, 123)";
    var platformDistFromTop = 120;
    var platformThickness = .5;

    //This is where the walking skins are stored.
    var playerWalkSkins = [
        "Drawing (1).png", "Drawing (2).png",
        "Drawing (3).png", "Drawing (4).png", 
        "Drawing (5).png", "Drawing (6).png",           
        "Drawing (7).png", "Drawing (8).png",
        "Drawing (9).png", "Drawing (10).png", 
        "Drawing (11).png", "Drawing (12).png"
    ]

    var playerXPos = canvas.width / 2;
    var playerYPos = platformDistFromTop;
    var playerSpeed = 4;
    var currentSkin = 0;

    var playerImg = new Image();


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

        if (event.keyCode == 37) { //left arrow

            playerXPos -= playerSpeed;
            if (currentSkin == playerWalkSkins.length-1) {
                currentSkin = 0;
        }
        else {
            currentSkin++;
        }
    }

    else if (event.keycode == 39) { //right arrow

        playerXPos += playerSpeed;
        if (currentSkin == playerWalkSkins.length-1) {
            currentSkin = 0;
        }
        else {
            currentSkin++;
        }
    }

    }, false);



    //Animation zone
    setInterval(function() {
        background.fillStyle = backgroundColor;
        background.fillRect(0, 0, canvas.width, canvas.height);

        platform.fillStyle = platformColor;
        platform.fillRect(0, platformDistFromTop, canvas.width, platformThickness);

        playerImg.src = playerWalkSkins[currentSkin];
        player.drawImage(playerImg, playerXPos, platformDistFromTop-57, 60, 60);
    }, 5);
}

问题可能在于活动列表。我已经制作了其他程序,事件监听器正常工作,我看不出有任何区别。左箭头是正常工作的箭头。

感谢您的帮助,我希望我能继续我的项目。

1 个答案:

答案 0 :(得分:1)

问题是您的第二个event.keycode应该阅读event.keyCode - 这个案例在Javascript对象中很重要。如果您仍然被困或需要任何帮助,请告诉我。