Day 4 – Working with these weird radian things

There are often times that we’re forced to supply angles in radians rather than degrees, here’s one you might recognise:

// startAngle and endAngle must be given in radians!
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);

Luckily we can convert between degrees and radians, because one degree is equal to PI / 180 radians:

var one_degree_in_radians = 1 * Math.PI / 180;
var five_degrees_in_radians = 5 * Math.PI / 180;

Conversely, one radian is equal to 180 / PI degrees:

var one_radian_in_degrees = 1 * 180 / Math.PI;
var five_radians_in_degrees = 5 * 180 / Math.PI;

So let’s use this knowledge to create variables that make converting between degrees and radians easier:

// One degree in radians
var TO_RADIANS = Math.PI / 180;
 
// One radian in degrees
var TO_DEGREES = 180 / Math.PI;
 
var three_degrees_in_radians = 3 * TO_RADIANS;
var two_radians_in_degrees = 2 * TO_DEGREES;

Nothing can stop us now…

// 360 degree arc
ctx.arc(10, 10, 50, 0, 360 * TO_RADIANS, false);
 
// Sine, Cosine, etc require angles in radians:
var sineX = Math.sin(90 * TO_RADIANS);

Begone, radians!