HSL to RGB color conversion

后端 未结 21 2690
忘了有多久
忘了有多久 2020-11-22 01:59

I am looking for a JavaScript / PHP algorithm to convert between HSL color to RGB.

It seems to me that HSL is not very widely used so I am not having much luck search

21条回答
  •  北海茫月
    2020-11-22 02:30

    For all who said that Garry Tan solution converting incorrect from RGB to HSL and back. It because he left out fraction part of number in his code. I corrected his code (javascript). Sorry for link on russian languadge, but on english absent - HSL-wiki

    function toHsl(r, g, b)
    {
        r /= 255.0;
        g /= 255.0;
        b /= 255.0;
        var max = Math.max(r, g, b);
        var min = Math.min(r, g, b);
        var h, s, l = (max + min) / 2.0;
    
        if(max == min)
        {
            h = s = 0; 
        }
        else
        {
            var d = max - min;
            s = (l > 0.5 ? d / (2.0 - max - min) : d / (max + min));
    
            if(max == r && g >= b)
            {
                h = 1.0472 * (g - b) / d ;
            }
            else if(max == r && g < b)
            {
                h = 1.0472 * (g - b) / d + 6.2832;
            }
            else if(max == g)
            {
                h = 1.0472 * (b - r) / d + 2.0944;
            }
            else if(max == b)
            {
                h = 1.0472 * (r - g) / d + 4.1888;
            }
        }
        return {
            str: 'hsl(' + parseInt(h / 6.2832 * 360.0 + 0.5) + ',' + parseInt(s * 100.0 + 0.5) + '%,' + parseInt(l * 100.0 + 0.5) + '%)',
            obj: { h: parseInt(h / 6.2832 * 360.0 + 0.5), s: parseInt(s * 100.0 + 0.5), l: parseInt(l * 100.0 + 0.5) }
        };
    };
    

提交回复
热议问题