20

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.

Zong
  • 6,160
  • 5
  • 32
  • 46
user3610762
  • 417
  • 1
  • 5
  • 14
  • possible duplicate of [How to generate light colour shades in javascript](http://stackoverflow.com/questions/11225050/how-to-generate-light-colour-shades-in-javascript) – adeneo May 12 '14 at 05:53

5 Answers5

35

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;
}
Community
  • 1
  • 1
Kruga
  • 721
  • 5
  • 18
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

Aliendroid
  • 515
  • 3
  • 9
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) +
    ')';
}
Naman Goel
  • 1,525
  • 11
  • 16
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
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)));
}
Weilory
  • 2,621
  • 19
  • 35