SassColor.hwb constructor

SassColor.hwb(
  1. num hue,
  2. num whiteness,
  3. num blackness, [
  4. num? alpha = 1,
])

Creates an HWB color.

Throws a RangeError if whiteness or blackness aren't between 0 and 100, or if alpha isn't between 0 and 1.

Implementation

factory SassColor.hwb(num hue, num whiteness, num blackness,
    [num? alpha = 1]) {
  // From https://www.w3.org/TR/css-color-4/#hwb-to-rgb
  var scaledHue = hue % 360 / 360;
  var scaledWhiteness =
      fuzzyAssertRange(whiteness.toDouble(), 0, 100, "whiteness") / 100;
  var scaledBlackness =
      fuzzyAssertRange(blackness.toDouble(), 0, 100, "blackness") / 100;

  var sum = scaledWhiteness + scaledBlackness;
  if (sum > 1) {
    scaledWhiteness /= sum;
    scaledBlackness /= sum;
  }

  var factor = 1 - scaledWhiteness - scaledBlackness;
  int toRgb(double hue) {
    var channel = _hueToRgb(0, 1, hue) * factor + scaledWhiteness;
    return fuzzyRound(channel * 255);
  }

  // Because HWB is (currently) used much less frequently than HSL or RGB, we
  // don't cache its values because we expect the memory overhead of doing so
  // to outweigh the cost of recalculating it on access. Instead, we eagerly
  // convert it to RGB and then convert back if necessary.
  return SassColor.rgb(toRgb(scaledHue + 1 / 3), toRgb(scaledHue),
      toRgb(scaledHue - 1 / 3), alpha);
}