Skip to content

Instantly share code, notes, and snippets.

@laziel laziel/color-comparison.js
Last active Oct 11, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.