如何在Javascript中生成随机柔和(或更亮)的颜色? [英] How to generate random pastel (or brighter) color in Javascript?

查看:157
本文介绍了如何在Javascript中生成随机柔和(或更亮)的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个简单的网站,当我点击一个按钮时会给出一个随机引用,然后,背景颜色会发生变化。问题是,有时背景颜色太深,字体是黑色的,因此人无法读取报价。

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 if there is any way to create a random color code using just bright colors, or pastel colors?

我得到此代码以生成随机颜色。我尝试编辑只获得 A F 字符串但没有成功:

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)

非常感谢您提前。

推荐答案

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

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

hsl(色调,饱和度%,亮度%)

其中 hue 在0-360度范围内没有单位标记,且饱和度亮度是具有尾随符号的百分比。

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

注意


  • 所有亮颜色的饱和度值均为100%,亮度值为50 %:

  • all the "bright" colors have a saturation value of 100% and a lightness value of 50%:

色调0 - > < img src =https://i.stack.imgur.com/QqkeF.pngalt =HSL饱和色圈> < - hue 360​​

hue 0 --> <-- hue 360

所有颜色都与白色混合 - 随着亮度的增加而变得更加柔和。无论色调和饱和度的值是多少,亮度值100%都会产生白色。

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

当饱和度减少时,所有颜色都会与灰色混合并且变得更米色或灰色,具体取决于饱和度有多低。

all colors blend with grey as the saturation decreases and become more "beige" or "grey" depending on how low the saturation gets.

所有颜色都与黑色混合作为亮度降低。无论色调和饱和度值是多少,亮度值为0%都会产生黑色。

all colors blend with black as the lightness decreases. A lightness value of 0% creates black no matter what the hue and saturation values are.

作为示例设置身体背景为随机柔和色,饱和度范围为25-95%,亮度范围为85-95%:

As an example that sets the body background to a random pastel color with saturation in range 25-95% and lightness in range 85-95%:

var cssHSL = "hsl(" + 360 * Math.random() + ',' +
                 (25 + 70 * Math.random()) + '%,' + 
                 (85 + 10 * Math.random()) + '%)';

document.body.style.backgroundColor = cssHSL;

这篇关于如何在Javascript中生成随机柔和(或更亮)的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆