21

Below is my code that shows all types of color like dark blue,light blue,dark pink,light pink etc. But I want to get only light colors using JavaScript. Is it possible?

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

How can I do it? Thank you.

1

5 Answers 5

40

You can also use HSL colors.

HSL stands for hue, saturation, and lightness - and represents a cylindrical-coordinate representation of colors.

An HSL color value is specified with: hsl(hue, saturation, lightness).

Hue is a degree on the color wheel (from 0 to 360) - 0 (or 360) is red, 120 is green, 240 is blue. Saturation is a percentage value; 0% means a shade of gray and 100% is the full color. Lightness is also a percentage; 0% is black, 100% is white.

function getRandomColor() {
  color = "hsl(" + Math.random() * 360 + ", 100%, 75%)";
  return color;
}
2
  • 1
    Excellent answer. Worked great for me because I was also wanting to avoid white and grey.
    – Xandor
    Commented May 4, 2019 at 18:59
  • Yeah, this is exactly what I was looking for, light colors other than white and grey. Works perfect Commented Nov 14, 2019 at 2:35
33

you can do so by cutting the string off forcing the random to be high number in HEX

      function getRandomColor() {
                var letters = 'BCDEF'.split('');
                var color = '#';
                for (var i = 0; i < 6; i++ ) {
                    color += letters[Math.floor(Math.random() * letters.length)];
                }
                return color;
            }

quick dirty way

1
  • 2
    what I did was, I added an extra '66' at end of the RGB color and made it RGBA so every color becomes light on its own :-) Commented Feb 16, 2018 at 18:28
5

A small improvement:

function getRandomColor() {
  return 'rgb(' + 
    (Math.floor(Math.random()*56)+200) + ', ' +
    (Math.floor(Math.random()*56)+200) + ', ' +
    (Math.floor(Math.random()*56)+200) +
    ')';
}
1
const generateRandomLightColor = () => {
    const red = Math.floor(Math.random() * 255)
    const green = Math.floor(Math.random() * 255)
    const blue = Math.floor(Math.random() * 255)
    const opacity = 0.5
    return `rgba(${red}, ${green}, ${blue}, ${opacity})`
}
0
0
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getRandomColor() {
  return Array.from({length: 3}, ii=>Math.floor(getRandomInt(130, 240)));
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.