title: Canvas bouncing ball randomly passes left border
body: <p>I'm trying to make a canvas background with randomly moving balls. Balls will bounce when they reach the edge. It should be easy but apparently I missed something.</p>
  
  <p>Right now, it looks pretty good for the first few second, but after a while, these balls just wouldn't bother to pass the left border, and never bounce back. I've been trying to figure out for days, and failed. Any help is appreciated.</p>
  
  <pre><code>update(delta, canvas) {
  
      let deltaX = delta * Math.cos(this.movingDirection * Math.PI / 180);
      let deltaY = delta * Math.sin(this.movingDirection * Math.PI / 180);
  
      this.axisX += deltaX;
      this.axisY += deltaY;
  
      //set border
      if (this.axisX &gt; (canvas.width)) {
          if (this.movingDirection &gt; 270 &amp;&amp; this.movingDirection &lt; 360) {
              this.movingDirection = 180 + this.movingDirection;
          } else if (this.movingDirection &lt; 90 &amp;&amp; this.movingDirection &gt; 0) {
                  this.movingDirection = 180 - this.movingDirection;
          }
      }
      if (this.axisX &lt; 0) {
          if (this.movingDirection &gt; 180 &amp;&amp; this.movingDirection &lt; 270) {
              this.movingDirection = 540 - this.movingDirection;
          } else if (this.movingDirection &lt;= 180 &amp;&amp; this.movingDirection &gt; 90) {
              this.movingDirection = 180 - this.movingDirection;
          }
      }
  
      if (this.axisY &gt; (canvas.height) || this.axisY &lt; 0) {
          if (this.movingDirection &gt; 180 ) {
              this.movingDirection = 360 - this.movingDirection;
          } else if (this.movingDirection &lt;= 180) {
              this.movingDirection = 360 - this.movingDirection;
          }
      }
      this.draw();
  }
  </code></pre>
  
  <p>this.movingDirection is a randomly generated number between 0 and 360.</p>
  
  <p>Here is a complete example <a href="https://jsfiddle.net/calmdown/qr89b034/1/" rel="nofollow noreferrer">https://jsfiddle.net/calmdown/qr89b034/1/</a></p>
  
  <p>Thank you!</p>