Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
Change speed of a rectangle in a canvas

It's my first question here. I just learn canvas in JavaScript and I found a problem while adding the speed. I want to stop the rectangle if its x exceeds the width of the canvas. I am just a beginner, so please help me.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #canvas{
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="400" height="400">Your browser doesn't support canvas</canvas>
    <script>
        var canvas = document.getElementById('canvas');
        var cnxt = canvas.getContext('2d');
        x = 0;
        y = 50;
        var t;
        function draw(){
            cnxt.clearRect(0,0,400,400);
            cnxt.beginPath();
            cnxt.rect(x,y,25,25);
            cnxt.fillStyle = 'red';
            cnxt.fill();
            var timePassed = (performance.now()-t)/1000;
            var fps = Math.round(1/ timePassed);
            
            let speed = 100;
            
            cnxt.font = '25px Arial';
            cnxt.fillStyle = 'black';
            cnxt.fillText("FPS: " + fps, 20,30);
            t = performance.now();
            
            x += (speed * timePassed);
            if (x >= 400 - 25){
                speed = 0;
            }
            window.requestAnimationFrame(draw);
            
        }
        draw();

    </script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda