Skip to content

Instantly share code, notes, and snippets.

@dgrebb
Created January 20, 2024 04:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dgrebb/b5e984bcdbb95a5dda7392401b50f607 to your computer and use it in GitHub Desktop.
Save dgrebb/b5e984bcdbb95a5dda7392401b50f607 to your computer and use it in GitHub Desktop.
Forget about your worries and your strife — have a contrast calculator figure out the best color to use against another (black or white).
/**
* Calculates and returns a high-contrast color (either black or white)
* for optimal readability when displayed on top of the provided color.
* The function uses the luminance formula to determine the brightness
* of the input color and returns either black or white based on a
* luminance threshold.
*
* @param {string} hexColor - The hex code of the background color.
* Should be a valid hex color code starting with '#'
* and followed by six hexadecimal characters.
* @returns {string} A hex code ('#000000' for black or '#FFFFFF' for white)
* representing the high-contrast color.
*
* @example
* // returns '#000000'
* getHighContrastColor("#00FF00");
*
* @example
* // returns '#FFFFFF'
* getHighContrastColor("#0000FF");
*/
export const getHighContrastColor = function (hexColor) {
// Convert hex color to RGB
const r = parseInt(hexColor.substring(1, 3), 16);
const g = parseInt(hexColor.substring(3, 5), 16);
const b = parseInt(hexColor.substring(5, 7), 16);
// Calculate luminance
const luminance = 0.299 * r + 0.587 * g + 0.114 * b;
// Return high contrast color
return luminance > 186 ? '#000000' : '#FFFFFF'; // 186 is a commonly used threshold ¯\_(ツ)_/¯
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment