Degrees to Radians

The html5 canvas api uses radians for rotation and drawing circles. But I, as an ape, use degrees. Because of this I find myself constantly writing the following methods to convert degrees to radians and vice versa.

Converting degrees to radians

function degToRad(deg) {
    return deg * (Math.PI / 180)
}

If you find yourself calling it alot or constantly looking for 90 degrees as radians. You may want to memoize the method or store the value as a constant.

const deg90 = degToRadians(90)

// or

const __degToRadCache = {}

function degToRadMemo(deg) {
    if(deg in __degToRadCache) return __degToRadCache[deg]

    const radians = degToRad(deg) 
    __degToRadCache[deg] = radians
    return radians
}

Converting radians to degrees

The inverse of the above, handy for debugging.

function radToDeg(rad) {
    return rad * (180 / Math.PI)
}

Until next time,

- Brian