How to generate random pastel (or brighter) color in Javascript?

Zzeks picture Zzeks · Apr 3, 2017 · Viewed 16.2k times · Source

I am building a simple website that gives a random quote when I click a button, and with that, the background color changes. The thing is that sometimes the background color is too dark and the font is black, and consequently the person can't read the quote.


My question:

Is there is any way to create a random color code using just bright colors, or pastel colors?


I got this code to generate a random color. I tried to edit to get only A to F strings but no success:

'#'+((1<<24)*(Math.random()+1)|0).toString(16).substr(1)

Thank you very much in advance.

Answer

traktor picture traktor · Apr 4, 2017

HSL Colors

Using HSL Colors colors may be the easiest. HSL color values are specified in CSS as

hsl( hue, saturation%, lightness%)

where hue is in range 0-360 (without a unit marker when using degrees), and both saturation and lightness are percentages with a trailing % sign.

Note

  • "Bright" colors refer to the colors of an RGB color wheel formed by starting at red and then blending pure red into green, pure green into blue, and finally pure blue back into red again.

  • In HSL color space, bright colors are represented by a hue based on their position on the color wheel with 100% saturation and a lightness value of 50%:

    hue 0HSL saturated color circle ◀ hue 360
    saturation: 100%
    lightness: 50%

  • Colors blend with white - and become more "pastel" as lightness increases above 50%. A lightness value of 100% creates white regardless of what the values of hue and saturation are.

  • Colors blend with grey as the saturation decreases and become more washed out depending on how low the saturation gets. A saturation value of 0% creates a grey-scale tone based on lightness alone.

  • Colors blend with black as lightness decreases below 50%. A lightness value of 0% creates black no matter what the hue and saturation values are.

Warning

The human eye is least sensitive to the color blue. Black text on a blue background - or blue over black - is harder to read in comparison to other colors. If this becomes an issue for random color selection, example 2 shows one way to compensate.


Example 1: Some random pastel colors with saturation in range 25-95% and lightness in range 85-95%:

function getColor(){ 
  return "hsl(" + 360 * Math.random() + ',' +
             (25 + 70 * Math.random()) + '%,' + 
             (85 + 10 * Math.random()) + '%)'
}


// Generate 20 colors
for( var i = 20; i--; ){
  var item = document.createElement('div')
  item.style.cssText = `
    display:inline-block; 
    padding: 2em;
    margin:5px; 
    border-radius:50%;
    background: ${getColor()};
  `
  document.body.appendChild(item);
}


Example 2: This example demonstrates adjusting colors for the eye's lack of sensitivity to blue. It generates a boxed set of letters colored with hues in the range 0 to 340 presented on a black background.

"use strict";

// individual letter classes:
function letterCSS(letter, i, length, blueBoost) {
    let hue = Math.floor( i/length * 341); // between 0 and 340
    let saturation = 100;
    let lightness = 50;

    // color adjustment:
    if( blueBoost && hue > 215 && hue < 265) {
         const gain = 20;
         let blueness = 1 - Math.abs( hue-240)/25;
         let change  = Math.floor( gain * blueness);
         lightness += change;
         saturation -= change;
    }
    let hsl = `hsl(${hue}, ${saturation}%, ${lightness}%)`;

  return `.${letter} {
  color: ${hsl};
  border-color: ${hsl};
  background-color: black;
}
`   ;
}

// generate and display boxed letters of the alphabet
function letterBlocks() {
    let letters = Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    let cssText = "";
    let html = ""
    let blueBoost = document.getElementById("boost").checked;
    letters.forEach( (letter, i, a) => {
       cssText += letterCSS( letter, i, a.length, blueBoost);
       html  += ` <span class="letter ${letter}">${letter}<\/span> `;
    });
    let style = document.createElement("style");
    style.textContent = cssText;
    document.body.appendChild(style);
    let p = document.getElementById("blocks");
    p.innerHTML = html;
}
#blocks {
  line-height: 2.5rem;
}
.letter {
  display: inline-block;
  text-align: center;
  line-height: 2rem;
  font-size: 1.5rem;
  height: 2rem;
  width: 2rem;
  font-family: sans-serif;
  font-weight: bold;
  border-width: 0.125rem;
  border-style: solid;
  border-radius: 0.25rem;
}
<button type="button" onclick="letterBlocks()">Generate Letter Blocks</button><label>
- optionally lighten colors near pure blue:<input type="checkbox" id="boost">
</label>
<p id="blocks"></p>

Letter colors start out with full saturation and 50% lightness. Check the option box and click the button to adjust colors close to blue by increasing lightness and decreasing saturation.

  • "Close to blue" is hard coded to mean within 25 degree units of hue value 240,
  • The maximum adjustment amount is set by gain to 20 percentage units,
  • Demonstration code. Real code and adjustment values would be altered on a case by case basis depending on why and how color adjustments are being made.