Why doesn't this Javascript RGB to HSL code work?

前端 未结 4 1064
独厮守ぢ
独厮守ぢ 2020-11-27 07:31

I found this RGB to HSL script over at http://www.mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript. I can\'t find any other s

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 07:43

    Function below converts RGB color into Hue Saturation Brightness color like Photoshop color picker, results are in the ranges:

    • Hue 0-360 (degrees)
    • Saturation: 0-100 (%)
    • Brightness: 0-100 (%)

    I still don't understand why people use the term HSV (Hue Saturation Value) instead of HSB (Hue Saturation Brightness), anyway it's a matter fo terminology, the results are the same

       //Converts to color HSB object (code from here http://www.csgnetwork.com/csgcolorsel4.html with some improvements)
       function rgb2hsb(r, g, b)
       {    
        r /= 255; g /= 255; b /= 255; // Scale to unity.   
        var minVal = Math.min(r, g, b),
        maxVal = Math.max(r, g, b),
        delta = maxVal - minVal,
        HSB = {hue:0, sat:0, bri:maxVal},
        del_R, del_G, del_B;
    
        if( delta !== 0 )
        {
            HSB.sat = delta / maxVal;
            del_R = (((maxVal - r) / 6) + (delta / 2)) / delta;
            del_G = (((maxVal - g) / 6) + (delta / 2)) / delta;
            del_B = (((maxVal - b) / 6) + (delta / 2)) / delta;
    
            if (r === maxVal) {HSB.hue = del_B - del_G;}
            else if (g === maxVal) {HSB.hue = (1 / 3) + del_R - del_B;}
            else if (b === maxVal) {HSB.hue = (2 / 3) + del_G - del_R;}
    
            if (HSB.hue < 0) {HSB.hue += 1;}
            if (HSB.hue > 1) {HSB.hue -= 1;}
        }
    
        HSB.hue *= 360;
        HSB.sat *= 100;
        HSB.bri *= 100;
    
        return HSB;
       }
    

    Usage example:

    var hsb = rgb2hsb(126,210,22);
    alert("hue = " + hsb.hue + "saturation = " + hsb.sat + "brightness = " + hsb.bri);
    

提交回复
热议问题