convert Hsl to rgb and hex

后端 未结 6 2032
时光说笑
时光说笑 2020-11-27 07:47

I need a color converter to convert from hsl to rgb and hex value. I am going to do similar like this. I am using jquery and jquery ui range slider for this. Here is my co

6条回答
  •  Happy的楠姐
    2020-11-27 08:13

    I've made a small library that can easily convert colors.

    This is my HSL to RGB method, which uses a few other utility methods from the library:

    Color.hslToRgb = function(hsl, formatted) {
      var a, b, g, h, l, p, q, r, ref, s;
      if (isString(hsl)) {
        if (!hsl.match(Color.HSL_REGEX)) {
          return;
        }
        ref = hsl.match(/hsla?\((.+?)\)/)[1].split(',').map(function(value) {
          value.trim();
          return parseFloat(value);
        }), h = ref[0], s = ref[1], l = ref[2], a = ref[3];
      } else if ((isObject(hsl)) && (hasKeys(hsl, ['h', 's', 'l']))) {
        h = hsl.h, s = hsl.s, l = hsl.l, a = hsl.a;
      } else {
        return;
      }
      h /= 360;
      s /= 100;
      l /= 100;
      if (s === 0) {
        r = g = b = l;
      } else {
        q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        p = 2 * l - q;
        r = Color.hueToRgb(p, q, h + 1 / 3);
        g = Color.hueToRgb(p, q, h);
        b = Color.hueToRgb(p, q, h - 1 / 3);
      }
      return getRgb(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a, formatted);
    };
    

    If you don't want to use npm, the lib can also be found on GitHub.

提交回复
热议问题