Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!