lundi 25 avril 2022

How to avoid generating too black colors at random in JavaScript?

Whenever I click a button on the browser it displays a random color along with its rgb(r,g,b) code. I made 3 variables r, g, and b which produce random numbers from 0 to 255 using the basic logic of Math.floor(Math.random()*256);

My problem is that sometimes the random colors generated are too dark and the rgb code displayed along with them is black in color.

I tried writing a logic that whenever r+g+b < 300, toggle the h1 element's class which has a property of color white.

const h1 = document.querySelector('h1');
const button = document.querySelector("button");
h1.classList.add('h1');
//if (r+g+b < 500)
button.addEventListener('click', () => {
    changeColor();
});

const changeColor = (() => {
    const newColor = randomColor();
    document.body.style.backgroundColor = newColor;
    h1.innerText = newColor;
    }
);

const randomColor = (() => {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
})



Aucun commentaire:

Enregistrer un commentaire