Skip to content

Instantly share code, notes, and snippets.

@jurv
Created January 6, 2017 12:44
Show Gist options
  • Save jurv/bff64ce786dd5f6058f9d94e3c70fe47 to your computer and use it in GitHub Desktop.
Save jurv/bff64ce786dd5f6058f9d94e3c70fe47 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;
}
@6TELOIV
Copy link

6TELOIV commented Nov 8, 2024

Typescript version:

function shouldTextBeBlack(backgroundcolor: string) {
    return computeLuminence(backgroundcolor) > 0.179;
}

function computeLuminence(backgroundcolor: string) {
    var colors = hexToRgb(backgroundcolor);

    if (!colors) {
        throw new Error('Invalid color');
    }

    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: string): Record<string, number> | null {
    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