skip to Main Content

When I click the arrow keys (37, 38, 39, and 40) the variables of x and y change yet the position of the square given by ctx.fillRect(x, y, 100, 100); does not change. How come? And is there any solution?

<!DOCTYPE html>
<html>
<body>

<canvas id="canvasSpace" width="1460" height="710" style="border:2px solid #000000;"></canvas>

    <script>
        const canvas = document.getElementById("canvasSpace");
        const ctx = canvas.getContext("2d");
        let x = 735, y = 360
        ctx.fillRect(x, y, 100, 100);

        function moveLeft() {x -= 10;}
        function moveUp() {y += 10;}
        function moveRight() {x += 10;}
        function moveDown() {y -= 10;}

        function log() {
        alert("x = " + x)
        alert("y = " + y)
        }

        document.addEventListener('keydown', function(event) {
            if (event.keyCode == 37) {moveLeft();}
            if (event.keyCode == 38) {moveUp();}
            if (event.keyCode == 39) {moveRight();}
            if (event.keyCode == 40) {moveDown();}
            if (event.keyCode == 13) {log();}
        });
    </script>

</body>
</html>

I added the log function to trigger when the enter key (13) was pressed to make sure the variables change. Yet this doesn’t appear to be the problem as the variables do change.

2

Answers


  1. You aren’t calling fillRect again after you change the variables.

    Login or Signup to reply.
  2. The issue is because you don’t re-draw the canvas after you change the x and y values.

    You will also need to clear the canvas again before you re-draw it, otherwise the previous rect will still be visible.

    Here’s a working example, with the logic for key bindings made more succint:

    const canvas = document.getElementById("canvasSpace");
    const ctx = canvas.getContext("2d");
    let x = 35;
    let y = 60;
    
    function draw() {
      ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
      ctx.fillRect(x, y, 100, 100);
    }
    
    const keyMapping = {
      'ArrowLeft': () => x -= 10,
      'ArrowRight': () => x += 10,
      'ArrowUp': () => y -= 10,
      'ArrowDown': () => y += 10,
      'Enter': () => console.log(`${x}, ${y}`)
    } 
    
    document.addEventListener('keydown', e => {
      keyMapping[e.key]();
      draw();
    });
    
    draw();
    canvas {
      border: 2px solid #000000;
    }
    <canvas id="canvasSpace" width="600" height="175"></canvas>

    Note that the canvas size and starting x/y values were only changed in the example to make it fit in to the snippet editor better.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search