1

I'm trying to add a gradient to every element to each page, for now, I've achieved it but I've run into a problem.

If the gradient is too light my text is not visible, is there any way to check if the gradient color is too light and then change the text to black?

Here is my code

This is the gradients element = https://github.com/ghosh/uiGradients/blob/master/gradients.json

const cards = document.querySelectorAll('.card');
    cards.forEach((card)=>{
            let i = Math.floor(Math.random() * gradients.length);
            const color = gradients[i].colors;
            color.forEach((color)=> {
                let finalGradient = `background: linear-gradient(to right, ${color}, ${color}, ${color}) !important;`;
                card.style.cssText = finalGradient;
            })
        })
Lucjan Grzesik
  • 739
  • 5
  • 17
  • Possible duplicate of [Change text color based on brightness of the covered background area?](https://stackoverflow.com/questions/11867545/change-text-color-based-on-brightness-of-the-covered-background-area) – Heretic Monkey Sep 08 '19 at 21:16

1 Answers1

2

Here a function that I use to detect if a color is light or dark. You can use it and adapt to your code:

function isLightOrDark(color) {

    // Variables for red, green, blue values
    var r, g, b, hsp;

    // Check the format of the color, HEX or RGB?
    if (color.match(/^rgb/)) {

        // If HEX --> store the red, green, blue values in separate variables
        color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);

        r = color[1];
        g = color[2];
        b = color[3];
    } 
    else {

        // If RGB --> Convert it to HEX: http://gist.github.com/983661
        color = +("0x" + color.slice(1).replace( 
        color.length < 5 && /./g, '$&$&'));

        r = color >> 16;
        g = color >> 8 & 255;
        b = color & 255;
    }

    // HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
    hsp = Math.sqrt(
    0.299 * (r * r) +
    0.587 * (g * g) +
    0.114 * (b * b)
    );

    // Using the HSP value, determine whether the color is light or dark
    if (hsp>127.5) {

        return 'light';
    } 
    else {

        return 'dark';
    }
}
ManUtopiK
  • 4,495
  • 3
  • 38
  • 52