Farbtastic convert HSL back to RGB or Hex

前端 未结 2 1528
醉酒成梦
醉酒成梦 2020-12-22 05:57

Edit: Posting Solution

I wanted to create color swatches based on the color chosen in Farbtastic. I did my calculations on the HSL value, because i

相关标签:
2条回答
  • 2020-12-22 06:53

    Michael Jackson has this conversion, along with other colour conversions, in JavaScript, on his site.

    function hslToRgb(h, s, l) {
        var r, g, b;
    
        if (s == 0) {
            r = g = b = l; // achromatic
        } else {
            function hue2rgb(p, q, t) {
                if (t < 0) t += 1;
                if (t > 1) t -= 1;
                if (t < 1 / 6) return p + (q - p) * 6 * t;
                if (t < 1 / 2) return q;
                if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
                return p;
            }
    
            var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
            var p = 2 * l - q;
            r = hue2rgb(p, q, h + 1 / 3);
            g = hue2rgb(p, q, h);
            b = hue2rgb(p, q, h - 1 / 3);
        }
    
        return [r * 255, g * 255, b * 255];
    }
    
    0 讨论(0)
  • 2020-12-22 06:54

    I decided to seperate the functions and rewrite them a little so they work properly.
    Ended up with this :

    function hsl2rgb(h, s, l) {
        var m1, m2, hue;
        var r, g, b
        s /=100;
        l /= 100;
        if (s == 0)
            r = g = b = (l * 255);
        else {
            if (l <= 0.5)
                m2 = l * (s + 1);
            else
                m2 = l + s - l * s;
            m1 = l * 2 - m2;
            hue = h / 360;
            r = Math.round(HueToRgb(m1, m2, hue + 1/3));
            g = Math.round(HueToRgb(m1, m2, hue));
            b = Math.round(HueToRgb(m1, m2, hue - 1/3));
        }
        return {r: r, g: g, b: b};
    }
    
    function HueToRgb(m1, m2, hue) {
        var v;
        if (hue < 0)
            hue += 1;
        else if (hue > 1)
            hue -= 1;
    
        if (6 * hue < 1)
            v = m1 + (m2 - m1) * hue * 6;
        else if (2 * hue < 1)
            v = m2;
        else if (3 * hue < 2)
            v = m1 + (m2 - m1) * (2/3 - hue) * 6;
        else
            v = m1;
    
        return 255 * v;
    }
    

    It's called by doing:

    //the HSL values to use
    var h = 30;
    var s = 20;
    var l = 70;
    
    //call the function into a variable, returns an object rgb = {r:163, g:174, b:196}
    var rgb = hsl2rgb(h, s, l);
    
    //can now be accessed with rgb.r etc, and remember that the last two are percentages
    

    Here's a DEMONSTRATION

    If your variable newcolor is a string, you will have to do:

    var colorArray = newcolor.split(','),
        h = colorArray[0],  //  0.10434092941291336
        s = colorArray[1],  //  1
        l = colorArray[2];  //  0.756
    

    to get the HSL values into the right variables.

    0 讨论(0)
提交回复
热议问题