Calculate angle from points

by zerrax

HTML

<canvas id="canvas" width="300" height="300"></canvas>

CSS

canvas {
  background-color: white;
}

JavaScript

// ignore this
Number.prototype.loop = function loop() {
  var min, max;
  switch (arguments.length) {
    case 1:
      min = 0;
      max = arguments[0] || 0;
      break;
    case 2:
      min = arguments[0] || 0;
      max = arguments[1] || 0;
      break;
	}
  var num = this % max;
  if (num < min) {
    num += max;
  }
  return num;
};
// ignore this
CanvasRenderingContext2D.prototype.clear = function (color) {
  context.resetTransform();
  context.clearRect(0, 0, this.canvas.width, this.canvas.height);
};
// ignore this
CanvasRenderingContext2D.prototype.vertex = function (p, size, fill) {
  context.save();
  var size = size || 2;
  this.beginPath();
  this.arc(p.x, p.y, size, 0, 2 * Math.PI);
  this.shadowColor = "hsla(0, 0%, 20%,.5)";
  this.shadowBlur = size;
  this.fillStyle = fill || "gray";
  this.strokeStyle = "hsla(0, 0%, 20%,.75)";
  this.lineWidth = 0.5;
  this.fill();
  this.stroke();
  context.restore();
};

var context	= document.getElementById("canvas").getContext("2d");

// setting angle
var a = 0;

function draw() {
  context.clear();
	
  var point1 = {x:150, y:150};
  // point2 is placed relative to point1
  var point2 = pos(point1, 100, a);
  
  // rotate point2
  a += 0.5;
  a = a.loop(360); // if a > 360 => a = a % 360
  
  // make the points visible
  context.vertex(point1, 3, "red");
  context.vertex(point2, 3, "lime");
	
  // get point2's angle relative to point1
  var rel_angle = angle(point1.x, point1.y, point2.x, point2.y);
  
  // angle that is applied to point2
  context.fillText(a.toFixed(2), 10, 20);
  
  // angle that is retrieved from point2's position
  context.fillText(rel_angle.toFixed(2), 50, 20);
  
  requestAnimationFrame(draw);
}

draw();

function angle(originX, originY, targetX, targetY) {
    var dx = originX - targetX;
    var dy = originY - targetY;
    
    // var theta = Math.atan2(dy, dx);  // [0, Ⲡ] then [-Ⲡ, 0]; clockwise; 0° = west
    // theta *= 180 / Math.PI;          // [0, 180] then [-180, 0];...