RGB to HSL conversion

后端 未结 4 543
逝去的感伤
逝去的感伤 2020-12-13 01:51

I\'m creating a Color Picker tool and for the HSL slider, I need to be able to convert RGB to HSL. When I searched SO for a way to do the conversion, I found this question H

4条回答
  •  执笔经年
    2020-12-13 02:36

    This page provides a function for conversion between color spaces, including RGB to HSL.

    function RGBToHSL(r,g,b) {
      // Make r, g, and b fractions of 1
      r /= 255;
      g /= 255;
      b /= 255;
    
      // Find greatest and smallest channel values
      let cmin = Math.min(r,g,b),
          cmax = Math.max(r,g,b),
          delta = cmax - cmin,
          h = 0,
          s = 0,
          l = 0;
    
      // Calculate hue
      // No difference
      if (delta == 0)
        h = 0;
      // Red is max
      else if (cmax == r)
        h = ((g - b) / delta) % 6;
      // Green is max
      else if (cmax == g)
        h = (b - r) / delta + 2;
      // Blue is max
      else
        h = (r - g) / delta + 4;
    
      h = Math.round(h * 60);
    
      // Make negative hues positive behind 360°
      if (h < 0)
          h += 360;
    
      // Calculate lightness
      l = (cmax + cmin) / 2;
    
      // Calculate saturation
      s = delta == 0 ? 0 : delta / (1 - Math.abs(2 * l - 1));
    
      // Multiply l and s by 100
      s = +(s * 100).toFixed(1);
      l = +(l * 100).toFixed(1);
    
      return "hsl(" + h + "," + s + "%," + l + "%)";
    }
    

提交回复
热议问题