Last active
August 29, 2015 14:22
-
-
Save fiinix/e9f870e3c7fab274d3e3 to your computer and use it in GitHub Desktop.
Calculates the perceived brightness by measuring weighted distance in 3D RGB space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* =========================================================================== | |
* | |
* Polarize | |
* | |
* =========================================================================== | |
* | |
* Calculates the perceived brightness by measuring weighted distance | |
* in 3D RGB space | |
* | |
* Based on the work from: | |
* http://www.nbdtech.com/Blog/archive/2008/04/27/Calculating-the-Perceived-Brightness-of-a-Color.aspx | |
* | |
* http://cadik.posvete.cz/color_to_gray_evaluation/ | |
* | |
*/ | |
/** | |
* Default colors if not already defined in _variables.scss. | |
*/ | |
$black: #222 !default; | |
$white: #eee !default; | |
$polarize-black: $black !default; | |
$polarize-white: $white !default; | |
/* Every value in the range of 128-145 gives acceptable results */ | |
$polarize-cutoff: 130 !default; | |
$polarize-red-magic-number: 241 !default; | |
$polarize-green-magic-number: 691 !default; | |
$polarize-blue-magic-number: 68 !default; | |
$polarize-brightness-divisor: $polarize-red-magic-number + $polarize-green-magic-number + $polarize-blue-magic-number; | |
/* STILL TO DO: Figure out how to adjust the threshold based on luminance values of $white & $black */ | |
$polarize-cutoff: round((strip-units(lightness($polarize-white)) - strip-units(lightness($polarize-black))) * ($polarize-cutoff / 200)) +0%; | |
@function brightness($polarize-color) { | |
// Extract color components | |
$polarize-red-component: red($polarize-color); | |
$polarize-green-component: green($polarize-color); | |
$polarize-blue-component: blue($polarize-color); | |
// Calculate a brightness value in 3d color space between 0 and 255 | |
$number: sqrt((($polarize-red-component * $polarize-red-component * $polarize-red-magic-number) + ($polarize-green-component * $polarize-green-component * $polarize-green-magic-number) + ($polarize-blue-component * $polarize-blue-component * $polarize-blue-magic-number)) / $polarize-brightness-divisor); | |
// Convert to percentage and return | |
@return 100% * $number / 255; | |
} | |
@function contrast($polarize-color, $w: $polarize-white, $b: $polarize-black) { | |
@if brightness($polarize-color) < $polarize-cutoff { | |
@return $w; | |
} | |
@else { | |
@return $b; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment