如何在Javascript中生成随机的粉彩色(或更亮的颜色)?

39

问题:有没有办法(在JS中)只使用明亮的颜色淡色调的颜色来创建一个随机颜色代码?

我正在构建一个简单的网站,当我点击按钮时会随机显示一句名言,并且背景颜色也会跟着改变。问题是有时候背景颜色太暗了,字体是黑色的,人们就看不清那句话了。

我找到了这段代码来生成随机颜色。我尝试只获取字符串AF,但没有成功:

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

1
使用 hsl() 颜色,并在找到最佳饱和度和亮度值后随机化色调 https://jsfiddle.net/sva8ckpy/ - pawel
1
我猜 '#'+((1<<24)*(Math.random()+1)|0xc0c0c0).toString(16).substr(1) 可以解决问题 - 它应该将每个组件限制在 0xc0-0xff 范围内,但我不懂 JavaScript,所以任何事情都可能发生。0x808080 允许更多变化,但可能太多了。如果您需要更多灵活性,则需要使用更完整的答案,这些答案由可能知道 JavaScript 的人提供。 - sh1
3个回答

90

HSL颜色

使用HSL颜色可能是最简单的。在CSS中,HSL颜色值的指定方式为:

hsl( hue, saturation%, lightness%)

其中,hue 值的范围为 0-360(当使用角度时不带单位标记),而 saturationlightness 都是百分比值,范围为 0-100,末尾带有 % 标记。

注意

  • “明亮”颜色指的是 RGB 颜色轮上从红色开始,然后将纯红混合到绿色,将纯绿混合到蓝色,最后将纯蓝再次混合到红色的颜色。

  • 在 HSL 颜色空间中,明亮的颜色由其在颜色轮上的位置确定其色调,并具有饱和度值为 100% 和亮度值为 50%

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

  • 随着亮度值超过 50%,颜色会与白色混合,变得更加“蜡笔画”风格。亮度值为 100% 时,无论色调和饱和度的值如何,都会产生白色。

  • 随着饱和度的降低,颜色会与灰色混合,并根据饱和度的降低程度变得更加淡化。当饱和度值为 0% 时,根据亮度值单独创建灰色调。

  • 当亮度值低于 50% 时,颜色会与黑色混合。亮度值为 0% 时,无论色调和饱和度的值如何,都会产生黑色。

警告


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.


哇,这个解释让我大吃一惊,非常感谢您。 - Daniel Barde

19

只随机色调,速度更快。

HSLA 颜色是由 色调(Hue)、饱和度(Saturation)、亮度(Lightness) 和 透明度(Alpha)组成的。

Adjust the Lightness eq: 72% to adjust the whole pastel set.

function randomHSLA(){
    return `hsla(${~~(360 * Math.random())}, 70%,  72%, 0.8)`
}

rdm.onclick = () => document.body.style.background = randomHSLA()
rdm.click()
<button id="rdm">Random pastel color!</button>


1

您可以通过适当设置背景颜色属性来选择较浅的颜色,使用rgb。
rgb(0,0,0)为黑色,而rgb(255,255,255)为白色。因此,您可以使用接近于(但不高于)255的随机值。
一个例子(使用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);

你可以尝试不同的数值,直到找到自己喜欢的颜色 - 请记住,三个rgb值越接近,你得到的颜色就越接近灰色。例如,rgb(100,100,100)、rgb(221,221,221)和rgb(133,133,133)都是灰色调。不同的是,你得到的灰色会有多浅。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接