How to convert RGB value to HSL in javascript

0 votes
33 views
asked May 27, 2016 in java script by jonathan (3,105 points)

HI All

   How to convert RGB value to HSL in javascript. Please provide the valid code for the conversion 

Thanks in advance

1 Answer

0 votes
answered May 27, 2016 by admin (8,115 points)
function RGBtoHSL(r, g, b){
    r /= 255, g /= 255, b /= 255;
    var max = Math.max(r, g, b), min = Math.min(r, g, b);
    var h, s, l = (max + min) / 2;

    if(max == min){
        h = s = 0; // achromatic
    }else{
        var d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        switch(max){
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    return [ Math.round(h*360),  Math.round(s*100),  Math.round(l*100)];
}
...