3

I am generating random color with JavaScript. How do I know if the color produced is dark/light?

My JavaScriptcodes I use

btn.addEventListener('click', e => {
    const R = Math.floor(Math.random() * 256);
    const G = Math.floor(Math.random() * 256);
    const B = Math.floor(Math.random() * 256);

    body.style.backgroundColor = `rgb(${R}, ${G}, ${B})`;
    colorText.innerText = `R: ${R} \nG: ${G} \nB: ${B}`;
});
Gorkem
  • 33
  • 3
  • 1
    I suggest you to convert your color to grayscale, then define if color is greater or lower than 50% of brightness. – weeger Jan 22 '23 at 15:28
  • What's the definition of "dark" and "light" you want to use? There's a variety of ways this can be done, e.g., https://stackoverflow.com/q/12043187 and others. – Dave Newton Jan 22 '23 at 15:28
  • what do you consider a dark color? – Pycnonotus Jan 22 '23 at 15:29
  • 3
    check https://stackoverflow.com/questions/39118528/rgb-to-hsl-conversion you can convert rgb to hsl and then use L part to check whether color is light or dark – Iłya Bursov Jan 22 '23 at 15:29
  • @weeger posted the correct answer, but it was deleted. But it's the same as [written here](https://stackoverflow.com/questions/596216/formula-to-determine-perceived-brightness-of-rgb-color#:~:text=Luminance%20(perceived%20option%201)%3A%20(0.299*R%20%2B%200.587*G%20%2B%200.114*B)%20source) – Pieterjan Jan 22 '23 at 15:36

1 Answers1

1

As Iłya Bursov pointed out, you can calculate the lightness component (L) in HSL. The calculation for this is just 0.2126 * r + 0.7152 * g + 0.0722 * b. Because this value is range from 0 to 255, you can define "light colors" as any color with HSL lightness in the upper half of that range (>128), and vice versa for darkness. Like this:

const btn = document.getElementById('btn');
const colorText = document.getElementById('colorText');

btn.addEventListener('click', e => {
    const R = Math.floor(Math.random() * 256);
    const G = Math.floor(Math.random() * 256);
    const B = Math.floor(Math.random() * 256);
    
    let light = 0.2126 * R + 0.7152 * G + 0.0722 * B > 128;
    console.log(light)

    document.body.style.backgroundColor = `rgb(${R}, ${G}, ${B})`;
    colorText.innerText = `R: ${R} \nG: ${G} \nB: ${B}`;
});
<button id="btn">Button</button>
<br>
<span id="colorText"></span>
Michael M.
  • 10,486
  • 9
  • 18
  • 34