Skip to content

Instantly share code, notes, and snippets.

@Louis-7
Last active April 1, 2025 01:04
Show Gist options
  • Save Louis-7/965942c0045d5379f6f847e4178c82b8 to your computer and use it in GitHub Desktop.
Save Louis-7/965942c0045d5379f6f847e4178c82b8 to your computer and use it in GitHub Desktop.
Determine font color based on the background color
// suppose background color is: rbg(0, 23, 255)
function textColorBasedOnBackground(backgroundColor) {
backgroundColor = backgroundColor.substring(1);
const r = parseInt(backgroundColor.substring(0,2), 16); // 0 ~ 255
const g = parseInt(backgroundColor.substring(2,4), 16);
const b = parseInt(backgroundColor.substring(4,6), 16);
const srgb = [r / 255, g / 255, b / 255];
const x = srgb.map((i) => {
if (i <= 0.04045) {
return i / 12.92;
} else {
return Math.pow((i + 0.055) / 1.055, 2.4);
}
});
const L = 0.2126 * x[0] + 0.7152 * x[1] + 0.0722 * x[2];
return L > 0.179 ? "#000" : "#fff";
}
const backgroundColor = "rbg(0, 23, 255)";
const textColor = textColorBasedOnBackground(backgroundColor); // #fff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment