Skip to content

Instantly share code, notes, and snippets.

@laziel
Last active October 11, 2019 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laziel/3e727395591f18e79232f70683298fd6 to your computer and use it in GitHub Desktop.
Save laziel/3e727395591f18e79232f70683298fd6 to your computer and use it in GitHub Desktop.
Color comparison function for RGB (isLighterThan, isDarkerThan)
/** 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);
}
@laziel
Copy link
Author

laziel commented Oct 11, 2019

// Usage
isLighterThan({ r: 255, g: 250, b: 200 }, {r: 255, g: 250, b: 0 }); // true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment