1
resposta

Minha versão desse código, meio que já fazendo a base pro jogo PONG.

<!DOCTYPE html>
<html>
    <meta charset="utf-8">
    <canvas width="600" height="400"></canvas>
</html>

<script type="text/javascript">
    var myCanvas = document.querySelector('canvas');
    var brush = myCanvas.getContext('2d');
    var screenWidth = myCanvas.width;
    var screenHeight = myCanvas.height;
    const ball = {
        radius: 15,
        color: 'white',
        X: screenWidth / 2,
        Y: screenHeight / 2,
        speedX: 1.5,
        speedY: 0.5
    };

    setInterval(updateScreen, 10);

    function drawCircle (X, Y, radius, color) {
        brush.beginPath();
        brush.fillStyle = color;
        brush.arc(X, Y, radius, 0, 2 * Math.PI);
        brush.fill();
    }

    function clearScreen () {
        brush.clearRect(0, 0, screenWidth, screenHeight);
        brush.fillStyle = 'black';
        brush.fillRect(0, 0, screenWidth, screenHeight);
    }

    function updateScreen () {
        clearScreen();
        ballMovement();
        drawCircle(ball.X, ball.Y, ball.radius, ball.color);
    }

    function ballMovement () {
        if (ball.X - ball.radius - myCanvas.offsetLeft >= 0 &&
            ball.X + ball.radius <= screenWidth) {
            ball.X += ball.speedX;
        }
        else {
            ball.speedX = -1 * ball.speedX;
            ball.X += ball.speedX;
        }
        if (ball.Y - ball.radius - myCanvas.offsetTop > 0 &&
            ball.Y + ball.radius < screenHeight) {
            ball.Y += ball.speedY;
        }
        else {
            ball.speedY = -1 * ball.speedY;
            ball.Y += ball.speedY;
        }
    }
</script>
1 resposta

Olá, Daniel! Tudo bem por aí?

Sua solução ficou muito bacana, mandou bem.

Deixo apenas como observação para corrigir o fechamento da tag HTML .

Caso tenha ficado com alguma dúvida não deixe de compartilhar com a gente.

Bons estudos e até mais!