HSL to RGB color conversion

后端 未结 21 2738
忘了有多久
忘了有多久 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:18

    For when you need RGB to HSV and vice versa instead:

    function rgbToHsv(r, g, b)
    {
        r /= 255, g /= 255, b /= 255;
    
        var min = Math.min(r, g, b),
        max = Math.max(r, g, b),
        delta = max - min,
        h = 0, s = 0, v = max;
    
        if (min != max)
        {
            s = (delta / max);
    
            switch (max)
            {
                case r: h = (g - b) / delta + (g < b ? 6 : 0); break;
                case g: h = (b - r) / delta + 2; break;
                case b: h = (r - g) / delta + 4; break;
            }
    
            h /= 6;
        }
    
        return [h, s, v];
    }
    
    function hsvToRgb(h, s, v)
    {
        var step = h / (1 / 6),
        pos = step - Math.floor(step), // the hue position within the current step
        m = (Math.floor(step) % 2) ? (1 - pos) * v : pos * v, // mix color value adjusted to the brightness(v)
        max = 1 * v,
        min = (1 - s) * v,
        med = m + ((1 - s) * (v - m)),
        r, g, b;
    
        switch (Math.floor(step))
        {
            case 0:
                r = max;
                g = med;
                b = min;
                break;
            case 1:
                r = med;
                g = max;
                b = min;
                break;
            case 2:
                r = min;
                g = max;
                b = med;
                break;
            case 3:
                r = min;
                g = med;
                b = max;
                break;
            case 4:
                r = med;
                g = min;
                b = max;
                break;
            case 5:
                r = max;
                g = min;
                b = med;
                break;
        }
    
        return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
    }
    

提交回复
热议问题