'Sass function for determining the luminance of a color

I've found a half-dozen functions online for determining the luminance of a color in Sass. They are all almost identical, but none of them are working - all throwing the same error:

invalid operands for multiplication

This is the function I am currently using:

@function luminance($color){
    $rgba: red($color), green($color), blue($color);
    $rgba2: ();

    @for $i from 1 through 3 {
        $rgb: nth($rgba, $i);
        $rgb: $rgb / 255;
        $rgb: if($rgb < .03928, $rgb / 12.92, pow(($rgb + .055) / 1.055, 2.4));
        $rgba2: append($rgba2, $rgb);
    }

    @return (.2126 * nth($rgba2, 1) + .7152 * nth($rgba2, 2) + 0.0722 * nth($rgba2, 3))*100;
}

The error is referring to the last line in that function. All of the other functions I have tried (which work the same basic way) throw the same error.



Solution 1:[1]

Math is now part of the build-in Sass modules


@use 'sass:color';
@use 'sass:math';
@use 'sass:map';

@function luminance($color) {
  $rgb: (
    'r': color.red($color),
    'g': color.green($color),
    'b': color.blue($color)
  );

  @each $channel, $value in $rgb {
    $value: math.div($value, 255);

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

    $rgb: map.merge($rgb, ($channel: $value));
  }

  @return 
    (map.get($rgb, 'r') * .2126) + 
    (map.get($rgb, 'g') * .7152) + 
    (map.get($rgb, 'b') * .0722)
  ;
}


.test-luminance {
   tomato: luminance(tomato);  // 0.3063861272
   orange: luminance(orange);  // 0.4817026704  
   olive : luminance(olive);   // 0.200275372
   lime  : luminance(lime);    // 0.7152 
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jakob E