function angle(cx, cy, ex, ey) {
var dy = ey - cy;
var dx = ex - cx;
var theta = Math.atan2(dy, dx); // range (-PI, PI]
theta *= 180 / Math.PI; // rads to degs, range (-180, 180]
return theta;
}
function angle360(cx, cy, ex, ey) {
var theta = angle(cx, cy, ex, ey); // range (-180, 180]
if (theta < 0) theta = 360 + theta; // range [0, 360)
return theta;
}
show("right", 0, 0, 1, 0);
show("top right", 0, 0, 1, 1);
show("top", 0, 0, 0, 1);
show("top left", 0, 0, -1, 1);
show("left", 0, 0, -1, 0);
show("bottom left", 0, 0, -1, -1);
show("bottom", 0, 0, 0, -1);
show("bottom right", 0, 0, 1, -1);
// IGNORE BELOW HERE (all presentational stuff)
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
padding: 2px 4px;
}
tr > td:not(:first-child) {
text-align: center;
}
tfoot {
font-style: italic;
}
<table>
<thead>
<tr><th>Direction*</th><th>Start</th><th>End</th><th>Angle</th><th>Angle 360</th></tr>
</thead>
<tfoot>
<tr><td colspan="5">* Cartesian coordinate system<br>positive x pointing right, and positive y pointing up.</td>
</tfoot>
<tbody id="angles">
</tbody>
</table>
<script>
function show(label, cx, cy, ex, ey) {
var row = "<tr>";
row += "<td>" + label + "</td>";
row += "<td>" + [cx, cy] + "</td>";
row += "<td>" + [ex, ey] + "</td>";
row += "<td>" + angle(cx, cy, ex, ey) + "</td>";
row += "<td>" + angle360(cx, cy, ex, ey) + "</td>";
row += "</tr>";
document.getElementById("angles").innerHTML += row;
}
</script>