Toggle text color according to background color

Asked

Viewed 174 times

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 clear, the text turns black, and if it’s dark, the text turns white.

I tried looking for the site in question, but I forgot. It was more or less like this: The text stood on top of an article cover, so, as the article cover may vary in color, the text adapted to the background (image)

How is it done?

1 answer

1


You need a function that receives hexadecimal background to be able to break it into rgb and then calculate whether the source should be dark or light from the rgb values, thus returning the font color. Follow 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" );
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.