HSL to RGB color conversion

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

    With H, S,and L in [0,1] range:

    ConvertHslToRgb: function (iHsl)
    {
        var min, sv, sextant, fract, vsf;
    
        var v = (iHsl.l <= 0.5) ? (iHsl.l * (1 + iHsl.s)) : (iHsl.l + iHsl.s - iHsl.l * iHsl.s);
        if (v === 0)
            return { Red: 0, Green: 0, Blue: 0 };
    
        min = 2 * iHsl.l - v;
        sv = (v - min) / v;
        var h = (6 * iHsl.h) % 6;
        sextant = Math.floor(h);
        fract = h - sextant;
        vsf = v * sv * fract;
    
        switch (sextant)
        {
            case 0: return { r: v, g: min + vsf, b: min };
            case 1: return { r: v - vsf, g: v, b: min };
            case 2: return { r: min, g: v, b: min + vsf };
            case 3: return { r: min, g: v - vsf, b: v };
            case 4: return { r: min + vsf, g: min, b: v };
            case 5: return { r: v, g: min, b: v - vsf };
        }
    }
    

提交回复
热议问题