Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I capture the dark color?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading