Skip to content

Instantly share code, notes, and snippets.

@dcyou
Forked from jurv/color.js
Created December 6, 2022 08:39
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 dcyou/c302895c0421211a6b580d80783e9191 to your computer and use it in GitHub Desktop.
Save dcyou/c302895c0421211a6b580d80783e9191 to your computer and use it in GitHub Desktop.
JS - Check if text color should be black or white, based on the background color
function shouldTextBeBlack (backgroundcolor) {
return computeLuminence(backgroundcolor) > 0.179;
}
function computeLuminence(backgroundcolor) {
var colors = hexToRgb(backgroundcolor);
var components = ['r', 'g', 'b'];
for (var i in components) {
var c = components[i];
colors[c] = colors[c] / 255.0;
if (colors[c] <= 0.03928) {
colors[c] = colors[c]/12.92;
} else {
colors[c] = Math.pow (((colors[c] + 0.055) / 1.055), 2.4);
}
}
var luminence = 0.2126 * colors.r + 0.7152 * colors.g + 0.0722 * colors.b;
return luminence;
}
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment