使用箭头键在画布上移动图像

时间:2018-04-20 14:22:01

标签: javascript html5-canvas eventhandler

当我使用箭头键时,我试图得到一个我称之为“Sword”的块来上下移动,我有事件监听器和处理程序但是由于某种原因他们只是没有互相交谈而且我不知道为什么。

这是HTML,它非常简单,只需绘制一个画布即可使用。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>17013455_assignment_2</title>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script src="17013455_ass2_task1.js"></script>
</html>

这是Javascript,画布上画有背景,“剑”画成一个盒子,我的键处理程序应该根据剑的高度和Y轴上的空间将剑移动到Y轴上。

window.onload=function () {
    var canvas = document.getElementById("canvas");
    var gc = canvas.getContext("2d");
    canvas.width = 640;
    canvas.height = 448;
    gc.clearRect(0, 0, canvas.width, canvas.height);
    var background = new Image();
    background.src = "https://i.imgur.com/9mPYXqC.png";


        //sword dimentions
        var swordHeight = 50;
        var swordWidth = 25;
        var swordX = 50;
        var swordY = 220;

        //controls for player
        var upPressed = false;
        var downPressed = false;

        if (downPressed && swordY < canvas.height - swordHeight) {
            swordY += 10;
        }
        else if (upPressed && swordY > 0) {
            swordY -= 10;
        }

    function keyUpHandler(e) {
        if (e.keyCode === 38) {
            upPressed = false;
        }
        else if (e.keyCode === 40) {
            downPressed = false;
        }
    }

    function drawSword() {
        /*Make a box to represent a sword until sprites are used*/
        gc.beginPath();
        gc.rect(swordX, swordY, swordWidth, swordHeight);
        gc.fillStyle = "#000000";
        gc.fill();
        gc.closePath();

    }

    function keyDownHandler(e) {
        if (e.keyCode === 38) {
            upPressed = true;
        }
        else if (e.keyCode === 40) {
            downPressed = true;
        }
    }

    function render() {
        background.onload = function () {
            gc.drawImage(background, 0, 0)};
        drawSword();

    }

    document.addEventListener("keydown", keyDownHandler, "false");
    document.addEventListener("keyup", keyUpHandler, "false");

    render();
    setInterval(render, 10);
};

1 个答案:

答案 0 :(得分:0)

移动此部分代码

if (downPressed && swordY < canvas.height - swordHeight) {
        swordY += 10;
    }
    else if (upPressed && swordY > 0) {
        swordY -= 10;
    }

到render()函数。 你的功能应如下所示:

function render() {
    if (downPressed && swordY < canvas.height - swordHeight) {
        swordY += 10;
    }
    else if (upPressed && swordY > 0) {
        swordY -= 10;
    }
    gc.drawImage(background, 0, 0)};
    drawSword();

}

和这部分

background.onload = function () {
        gc.drawImage(background, 0, 0)};

到window.onload = function(){}范围