Toggle text color according to background color

0

How can I change the color of a text, according to the background color in which it is inserted?

I've seen this a few times. It works like this: if the background is light, the text turns black, and if it's dark, the text goes white.

I've tried searching for the site in question, but I've forgotten. It was something like this: The text was on top of an article cover, so as the cover of the article may vary in color, the text fit the background

How is this done?

    
asked by anonymous 07.03.2017 / 14:41

1 answer

1

You need a function that receives the background hex to be able to break it into rgb and then calculate whether the font should be dark or light from the rgb values, thus returning the font color. Here is an example:

const TextColor = hex => {
    let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, (m, r, g, b) => {
        return r + r + g + g + b + b;
    });
    let rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    rgb = (rgb ? { r: parseInt(rgb[1], 16), g: parseInt(rgb[2], 16), b: parseInt(rgb[3], 16) } : { r: 0, g: 0, b: 0 });
    return '#' + (Math.round(((parseInt(rgb.r) * 299) + (parseInt(rgb.g) * 587) + (parseInt(rgb.b) * 114)) /1000) > 150 ? "555" : "FFF" );
}
    
07.03.2017 / 20:50