Search code examples
javascripthtmlcanvasrectangles

How to make rectangle not leave canvas using Javascript


So I have created a rectangle on a canvas using javascript like in this video: 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);
        }
    }
}

However when I press the keys to move the rectangle around when it reaches the edge it doesn't stop. How do create a function etc to keep it in the canvas and just stop when it reaches the edge?

Thanks for all your help!


Solution

  • You just need additional if-statements to do a check before moving. You need to make sure y > 0 before moving the square up, y < canvas.height - 30 (30 being the height of your square) before moving down, and same for x with widths. The code below should work for you:

    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);
            }
        }
    }