Home > database >  How do I capture the dark color?
How do I capture the dark color?

Time:01-23

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}`;
});

CodePudding user response:

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>

  • Related