Spot the bug - #191: Canvas Loop

A quirky animation snippet with a sneaky bug.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Spot the Bug - Tiny Animation</title>
  <style>
    body { display:flex; align-items:center; justify-content:center; height:100vh; background:#111; color:#fff; margin:0; }
    #stage { width:200px; height:200px; position:relative; }
    .orb { width:40px; height:40px; border-radius:50%; background:#4af; position:absolute; top:80px; left:0; }
  </style>
</head>
<body>
  <div id="stage">
    <div class="orb" id="dot"></div>
  </div>
  <script>
    // Simple loop that animates the orb across the stage
    const dot = document.getElementById('dot');
    let t = 0;
    function animate(){
      t += 0.05;
      const x = (Math.sin(t) * 80) + 60; // quirky path
      dot.style.left = x + 'px';
      requestAnimationFrame(animate);
    }
    // Start immediately
    animate();
  </script>
</body>
</html>

Reply with what is broken and how you would fix it.

Spot the Bug answer: The animation path updates the ‘left’ property but the orb may overflow the 200px stage due to value range; also the initial top is 80px which is fine, but missing bounds reset can cause it to go off-screen. However the actual bug is that the left value is a number (px) but the stage is positioned relatively; the calculation should constrain within 0-160px range to keep the orb on stage.

The fix:

const dot = document.getElementById('dot'); let t = 0; function animate(){ t += 0.05; const x = (Math.sin(t) * 60) + 60; // constrain to 0..120 to stay on stage dot.style.left = x + 'px'; requestAnimationFrame(animate); } animate();

Why:
The current code computes left using a sine-based expression but the amplitude (80) plus offset can place the orb outside the 0-200px stage, causing it to disappear off-screen. By narrowing the range to 0..120 (or another safe bound) the orb remains visible while preserving the playful path.

First-answer leaderboard

  1. @emmawalter5 - 15 (firsts) :trophy:
  2. @Apexcodes - 9 (firsts)
  3. @kirupa - 8 (firsts)
  4. @PipMuse - 5 (firsts)
  5. @adnanahmed - 2 (firsts)