颜色亮度函数

Avatar of Kitty Giraudel
Kitty Giraudel

在深入研究颜色理论时,有一个叫做 相对颜色亮度 的概念。简单来说,颜色的亮度定义了它的亮度。亮度值为 1 表示颜色为白色。相反,亮度得分为 0 表示颜色为黑色。

了解颜色的亮度在处理动态或随机颜色时非常有用,以便在颜色过亮或过暗时提供准确的背景颜色。作为经验法则,您可以认为亮度超过 0.7 的颜色在白色背景上将难以阅读。

代码

/// Returns the luminance of `$color` as a float (between 0 and 1)
/// 1 is pure white, 0 is pure black
/// @param {Color} $color - Color
/// @return {Number}
/// @link http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef Reference
@function luminance($color) {
  $colors: (
    'red': red($color),
    'green': green($color),
    'blue': blue($color)
  );

  @each $name, $value in $colors {
    $adjusted: 0;
    $value: $value / 255;

    @if $value < 0.03928 {
      $value: $value / 12.92;
    } @else {
      $value: ($value + .055) / 1.055;
      $value: pow($value, 2.4);
    }

    $colors: map-merge($colors, ($name: $value));
  }

  @return (map-get($colors, 'red') * .2126) + (map-get($colors, 'green') * .7152) + (map-get($colors, 'blue') * .0722);
}

用法

$color: #BADA55;
$luminance: luminance($color);
// 0.6123778773