1
resposta

Controlando a bolinha com as teclas

<canvas width="600" height="400"></canvas>

<script>
    var canvas = document.querySelector('canvas');
    var brush = canvas.getContext('2d');
    brush.fillStyle = 'lightgray';
    brush.fillRect(0, 0, 600, 400);

    var x = 20;
    var y = 20;

    var left = 37;
    var up = 38;
    var right = 39;
    var down = 40;

    var movement = 10;

    function drawCircle(x, y, radius) {

        brush.fillStyle = 'blue';
        brush.beginPath();
        brush.arc(x, y, radius, 0, 2 * Math.PI);
        brush.fill();
    }

    function cleanScreen() {

        brush.clearRect(0, 0, 600, 400);
    }

    function move() {

        cleanScreen();
        drawCircle(x, y, 10);
    }

    setInterval(move, 10);

    function controls(event) {
        if (event.keyCode == left) {
            x = x - movement;
        } else if (event.keyCode == up) {
            y = y - movement;
        } else if (event.keyCode == right) {
            x = x + movement;
        } else if (event.keyCode == down) {
            y = y + movement;
        }
        if (x < 20) {
            x = 20;
        }
        if (x > 580) {
            x = 580;
        }
        if (y < 20) {
            y = 20;
        }
        if (y > 380) {
            y = 380;
        }
    }
    document.onkeydown = controls;
</script>
1 resposta

Você é profissional, seu código ficou excelente!