rgbToHsl function

List<num> rgbToHsl (
  1. num r,
  2. num g,
  3. num b
)

Convert an RGB color to HSL, where r, g and b are in the range 0, 255. Returns a list h, s, l with values in the range 0, 1.

Implementation

List<num> rgbToHsl(num r, num g, num b) {
  r /= 255.0;
  g /= 255.0;
  b /= 255.0;
  var mx = max(r, max(g, b));
  var mn = min(r, min(g, b));
  num h;
  var l = (mx + mn) / 2.0;

  if (mx == mn) {
    return [0.0, 0.0, l];
  }

  var d = mx - mn;

  var s = l > 0.5 ? d / (2.0 - mx - mn) : d / (mx + mn);

  if (mx == r) {
    h = (g - b) / d + (g < b ? 6.0 : 0.0);
  } else if (mx == g) {
    h = (b - r) / d + 2.0;
  } else {
    h = (r - g) / d + 4.0;
  }

  h /= 6.0;

  return [h, s, l];
}