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

前端 未结 4 1080
迷失自我
迷失自我 2021-01-01 16:18

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

相关标签:
4条回答
  • 2021-01-01 16:28

    Using some solutions from above, and this one to generate a color from a string

    Here is a way you can generate a pastel (bright) color for a given string

    function getBrightColor(hash){ 
        return `hsla(${~~(360 * hash)},70%,70%,0.8)`
    }
    
    var stringToBrightColour = function(str) {
        var hash = 0;
        for (var i = 0; i < str.length; i++) {
            hash = str.charCodeAt(i) + ((hash << 5) - hash);
        }
        var brightColor= getBrightColor(hash);
        return brightColor;
    }
    
    document.body.style.backgroundColor = stringToBrightColour("the color from this string");
    

    https://jsfiddle.net/jovistruck/x6j3agen

    0 讨论(0)
  • 2021-01-01 16:35

    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 0 ▶ ◀ 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.
    0 讨论(0)
  • 2021-01-01 16:49

    By randomizing only the hue, it's faster.

    HSLA colors are made of Hue, saturation, lightness and alpha.

    Example, lightness to be adjusted as needed (third value).

    function randomHSL(){
        return "hsla(" + ~~(360 * Math.random()) + "," +
                        "70%,"+
                        "80%,1)"
      }
    
    rdm.onclick = (function(){
       document.body.style.backgroundColor = randomHSL()
    })
    rdm.click()
    <button id="rdm">Random pastel color!</button>

    Or similary:

    function randomHSL(){
        return `hsla(${~~(360 * Math.random())},70%,70%,0.8)`
      }
    
    rdm.onclick = (function(){
       document.body.style.backgroundColor = randomHSL()
    })
    rdm.click()
    <button id="rdm">Random pastel color!</button>

    0 讨论(0)
  • 2021-01-01 16:50

    You could choose among lighter colours by appropriately setting the background-color property using rgb.
    rgb(0,0,0) is black, while rgb(255,255,255) is white. You could therefore use random values which are closer to (but not higher than) 255.
    An example (using JQuery):

     var rand = Math.floor(Math.random() * 10);
     var colorQ = "rgb(" + (215 - rand * 3) + "," + (185 - rand * 5) + "," + (185 - rand * 10) + " )"; 
     $("body").css("background-color", colorQ);
    

    You can play around with the values until you find the colours that you prefer - keep in mind that the closer the 3 rgb values are to each other, the closer your colour will be to grey. E.g. rgb(100,100,100), rgb(221,221,221) and rgb(133,133,133) are all shades of grey. What changes is how light your grey will be.

    0 讨论(0)
提交回复
热议问题