如何使用 Javascript 使矩形不离开 canvas

How to make rectangle not leave canvas using Javascript

所以我使用 javascript 在 canvas 上创建了一个矩形,就像在这个视频中一样: 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);
        }
    }
}

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

感谢您的帮助!

您只需要额外的 if 语句在移动之前进行检查。在向上移动正方形之前,您需要确保 y > 0,在向下移动之前确保 y < 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);
        }
    }
}