Last active
October 11, 2019 09:53
-
-
Save laziel/3e727395591f18e79232f70683298fd6 to your computer and use it in GitHub Desktop.
Color comparison function for RGB (isLighterThan, isDarkerThan)
This file contains hidden or 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
/** Extracted from https://gist.github.com/alexandrudima/bda598fbed179a581986b634cc94ab8d */ | |
/** | |
* Returns the number in the set [0, 1]. | |
* - O => Darkest Black. | |
* - 1 => Lightest white. | |
* @see http://www.w3.org/TR/WCAG20/#relativeluminancedef | |
* | |
* @param {Object} color | |
* @param {Number} color.r | |
* @param {Number} color.g | |
* @param {Number} color.b | |
* @return {Number} | |
*/ | |
function getRelativeLuminance(color) { | |
const luminance = 0.2126 * _relativeLuminanceForComponent(color.r) | |
+ 0.7152 * _relativeLuminanceForComponent(color.g) | |
+ 0.0722 * _relativeLuminanceForComponent(color.b); | |
const decimal = Math.pow(10, 4); | |
return Math.round(luminance * decimal) / decimal; | |
} | |
function _relativeLuminanceForComponent(n) { | |
const c = n / 255; | |
return (c <= 0.03928) ? c / 12.92 : Math.pow(((c + 0.055) / 1.055), 2.4); | |
} | |
function isLighterThan(a, b) { | |
return getRelativeLuminance(a) > getRelativeLuminance(b); | |
} | |
function isDarkerThan(a, b) { | |
return getRelativeLuminance(a) < getRelativeLuminance(b); | |
} |
Author
laziel
commented
Oct 11, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment