javascript to convert rgb to hsl

Solutions on MaxInterview for javascript to convert rgb to hsl by the best coders in the world

showing results for - "javascript to convert rgb to hsl"
Barron
26 Jan 2020
1/**
2 * Converts an RGB color value to HSL. Conversion formula
3 * adapted from http://en.wikipedia.org/wiki/HSL_color_space.
4 * Assumes r, g, and b are contained in the set [0, 255] and
5 * returns h, s, and l in the set [0, 1].
6 *
7 * @param   {number}  r       The red color value
8 * @param   {number}  g       The green color value
9 * @param   {number}  b       The blue color value
10 * @return  {Array}           The HSL representation
11 */
12function rgbToHsl(r, g, b){
13    r /= 255, g /= 255, b /= 255;
14    var max = Math.max(r, g, b), min = Math.min(r, g, b);
15    var h, s, l = (max + min) / 2;
16
17    if(max == min){
18        h = s = 0; // achromatic
19    }else{
20        var d = max - min;
21        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
22        switch(max){
23            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
24            case g: h = (b - r) / d + 2; break;
25            case b: h = (r - g) / d + 4; break;
26        }
27        h /= 6;
28    }
29
30    return [h, s, l];
31}
32