Skip to content

Instantly share code, notes, and snippets.

@fazlurr
Created October 7, 2019 08:27
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 fazlurr/2adc07a6a91c599c0eaaf2d8424fdb53 to your computer and use it in GitHub Desktop.
Save fazlurr/2adc07a6a91c599c0eaaf2d8424fdb53 to your computer and use it in GitHub Desktop.
/**
* Get Color Contrast
* @param {string} hex Hexa Color Code
*/
export const getColorContrast = (hex) => {
const color = hexToRgb(hex);
const treshold = 186;
const contrast = color
&& (color.r * 0.299 + color.g * 0.587 + color.b * 0.114) > treshold ? 'black' : 'white';
// for (const key in color) {
// if (color.hasOwnProperty(key)) {
// let c = color[key];
// c = c / 255.0;
// if (c <= 0.03928) {
// c = c / 12.92;
// }
// else {
// c = ((c + 0.055) / 1.055) ^ 2.4;
// }
// color[key] = c;
// }
// }
// const L = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b;
// const luminanceTreshold = 0.179;
// const contrast = L > luminanceTreshold ? 'black' : 'white';
return contrast;
};
/**
* Get Text Color
* @param {string} hex Hexa Color Code
*/
export const getTextColor = (bgColor, lightColor, darkColor) => {
const contrast = getColorContrast(bgColor);
return contrast === 'black' ? darkColor : lightColor;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment