title: Why does my canvas circle not bounce properly?
body: <p>What I did is, initially the  circle is not visible. Whenever arrow keys are pressed, it forwards in the respective direction.</p>
  <p>Whenever the event is triggered the speed of the circle gets added and ultimately it goes out of the viewport. Also, please suggest me a better way to do it.</p>
  <p><strong>Source code</strong></p>
  <pre><code>var x = 100;
  var y = 150;
  var dx = 10;
  var dy = 10;
  var right = false;
  var left = false;
  var down = false;
  var up = false; 
  
  
  
  function animate() {
      requestAnimationFrame   (animate);
  
      c.beginPath();
      c.strokeStyle = &quot;purple&quot;;
      c.lineWidth = 10;
      c.fillStyle = &quot;red&quot;;
      c.arc(x, y, 30, 0, Math.PI * 2);
      c.stroke();
      c.fill();
      if (right) {
          x += dx;
      }
      if (left) {
          x -= dx;
      }
  
      if (up) {
          y -= dy;
      }
      if (down) {
          y += dy;
      }
      else if (x + 30 &gt; canvas.width || x - 30 &lt; 0) {
          dx = -dx;
      }
      else if (y + 30 &gt; canvas.height || y - 30 &lt; 0) {
          dy = -dy;
      }
  }
  
  
  
  
  
  window.addEventListener(&quot;keydown&quot;, handleKeyRight);
  function handleKeyRight(key) {
      if (key.keyCode == &quot;39&quot;) {
          right = true;
          left = false;
          up = false;
          down = false;
          animate();
  
      }
  }
  window.addEventListener(&quot;keydown&quot;, handleKeyLeft);
  function handleKeyLeft(key) {
      if (key.keyCode == &quot;37&quot;) {
          left = true;
          up = false;
          down = false;
          right = false;
          animate();
  
      }
  }
  
  
  
  window.addEventListener(&quot;keydown&quot;, handleKeyUp);
  function handleKeyUp(key) {
      if (key.keyCode == &quot;38&quot;) {
          up = true;
          down = false;
          right = false;
          left = false;
          animate();
  
      }
  }
  window.addEventListener(&quot;keydown&quot;, handleKeyDown);
  function handleKeyDown(key) {
      if (key.keyCode == &quot;40&quot;) {
          down = true;
          right = false;
          left = false;
          up = false;
          animate();
  
      }
  
  }
  </code></pre>