【问题标题】:How to make rectangle not leave canvas using Javascript如何使用Javascript使矩形不离开画布
【发布时间】:2017-09-24 23:54:07
【问题描述】:

所以我使用 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);
        }
    }
}

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

感谢您的帮助!

【问题讨论】:

  • 我的代码看起来一模一样。 - 什么代码?请edit您的问题提供上述代码。
  • 我已经添加了代码,我的意思是它在 youtube 视频中。

标签: javascript html canvas rectangles


【解决方案1】:

您只需要额外的 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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-04-11
    • 1970-01-01
    • 2019-07-05
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 2014-09-08
    相关资源
    最近更新 更多