如何使矩形不使用Javascript离开画布

时间:2017-09-24 23:54:07

标签: javascript html5 canvas rectangles

所以我在画布上使用javascript创建了一个矩形,如下所示: https://www.youtube.com/watch?v=8ZPlNOzLrdw

    window.onload = function()
    {

        var canvas = document.getElementById("c");

        canvas.addEventListener('keydown', moveIt, true);

        ctx = canvas.getContext("2d");

        ctx.fillRect(100, 100, 30, 30);

        var x = 100;
        var y = 100;


        function moveIt(e) 
    {

        if (e.keyCode == 38)
        {
          ctx.clearRect(0, 0, canvas.width, canvas.height); 
            y = y - 10;
            ctx.fillRect(x, y, 30, 30); 
        }

        if (e.keyCode == 40)
        {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        y = y + 10;
        ctx.fillRect(x, y, 30, 30);
        }

        if (e.keyCode == 37)
        {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        x = x - 10;
        ctx.fillRect(x, y, 30, 30);
        }

        if (e.keyCode == 39)
        {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        x = x + 10;
        ctx.fillRect(x, y, 30, 30);
        }
    }
}

然而,当我按下按钮在到达边缘时移动矩形时,它不会停止。如何创建一个函数等以将其保留在画布中并在到达边缘时停止?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

在移动之前,您只需要额外的if语句来进行检查。在向下移动之前,您需要确保y > 0y < canvas.height - 30(30为正方形的高度),然后向下移动,x的宽度相同。以下代码适合您:

function moveIt(e) {

    if (e.keyCode == 38){
        if(y > 0){
            ctx.clearRect(0, 0, canvas.width, canvas.height); 
            y = y - 10;
            ctx.fillRect(x, y, 30, 30); 
        }
    }

    if (e.keyCode == 40){
        if(y < canvas.height - 30){
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            y = y + 10;
            ctx.fillRect(x, y, 30, 30);
        }
    }

    if (e.keyCode == 37){
        if(x > 0){
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            x = x - 10;
            ctx.fillRect(x, y, 30, 30);
        }
    }

    if (e.keyCode == 39){
        if(x < canvas.width - 30){
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            x = x + 10;
            ctx.fillRect(x, y, 30, 30);
        }
    }
}