title: Javascript about angles
body: <p>I'm trying to make a rectangle follow the angle between it and the mouse. Basically if the angle between the mouse and the current angle of the rectangle is higher than the current angle of the rectangle, it adds 1 and will continue until condition is false. The opposite happens when the angle between the two is lower than the current angle of the rectangle. My problem here is the angle between the mouse and rectangle, after 180 degrees it goes becomes -180. This causes the rectangle to go around again instead of going to 181 degrees. I've tried figuring out a way around this but I somehow always ended up in the same problem.
  Thanks in advance, here is my code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt;
  &lt;canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"&gt;&lt;/canvas&gt;
  &lt;/body&gt;
  &lt;script&gt;
  var canvas = document.getElementById("ctx"),
      ctx = canvas.getContext("2d"),
      width = canvas.width = window.innerWidth,
      height = canvas.height = window.innerHeight,
      mouse,
      angle = 0;
  function test() {
      "use strict";
      var dX = mouse.X - 200,
          dY = mouse.Y - 200,
          rad = (Math.atan2(dY, dX)),
          deg = (rad * (180 / Math.PI)),
          player = {
              x : 200,
              y : 200,
              width : 40,
              height : 10,
              angle : 0,
              dAngle : 0
          };
      //Test
      if (deg &gt; angle) {
          angle += 1;
      } else if (deg) {
          angle -= 1;
      }
      ctx.clearRect(0, 0, width, height);
      ctx.translate(player.x, player.y);
      ctx.rotate((angle * Math.PI / 180));
      ctx.fillRect(0, -player.height / 2, player.width, player.height);
      //console.log("deg :" + deg + "angle : " + angle);
      ctx.setTransform(1, 0, 0, 1, 0, 0);
  }
  window.onmousemove = function (mm) {
      "use strict";
      mouse = {
          X : mm.clientX - document.getElementById('ctx').getBoundingClientRect().left,
          Y : mm.clientY - document.getElementById('ctx').getBoundingClientRect().top
      };
  };
  
  setInterval(test, 40);
    &lt;/script&gt;</code></pre>
  </div>
  </div>
  </p>