javascriptcsscolorsrgbcolor-palette

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


Question: Is there is any way (in JS) to create a random color code using just bright colors, or pastel colors?

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.

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

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

Solution

  • 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 0-100 with a trailing % sign.

    Note

    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.