Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda