Javascript - 生成随机深色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20114469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:45:52  来源:igfitidea点击:

Javascript - Generate random dark color

javascriptrandomcolors

提问by SexyMF

I have this method to generate me random colors for font:

我有这个方法来为我生成字体的随机颜色:

function getRandomRolor() {
     var letters = '0123456789ABCDEF'.split('');
     var color = '#';
     for (var i = 0; i < 6; i++) {
         color += letters[Math.round(Math.random() * 15)];
     }
     return color;
}  

The problem is that the font is always on white background, I want to generate dark colors.
Is it possible?
Thanks

问题是字体总是在白色背景上,我想生成深色。
是否可以?
谢谢

采纳答案by Tom Prats

You could use a custom function that takes a hex and darkens it by the percent lum. You can modify it to return whatever you want back

您可以使用自定义函数,该函数采用十六进制并将其变暗百分比lum。您可以修改它以返回您想要的任何内容

function ColorLuminance(hex, lum) {
  // validate hex string
  hex = String(hex).replace(/[^0-9a-f]/gi, '');
  if (hex.length < 6) {
    hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  }
  lum = lum || 0;

  // convert to decimal and change luminosity
  var rgb = "#", c, i;
  for (i = 0; i < 3; i++) {
    c = parseInt(hex.substr(i*2,2), 16);
    c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
    rgb += ("00"+c).substr(c.length);
  }

  return rgb;
}

You could also just use hsl(Hugh, Saturation, Luminosity or Lightness). The hsl link actually goes through the above code.

您也可以只使用hsl(Hugh、Saturation、Luminosity 或Lightness)。hsl 链接其实就是通过上面的代码。

回答by Ganesh Jadhav

Take any random digit from 0-5as the first digit of your color and then choose the rest of the five digits using your above code.

取任何随机数字0-5作为您颜色的第一个数字,然后使用上面的代码选择其余的五位数字。

JS Fiddle: http://jsfiddle.net/xP5v8/

JS小提琴:http: //jsfiddle.net/xP5v8/

var color,
       letters = '0123456789ABCDEF'.split('')
function AddDigitToColor(limit)
{
    color += letters[Math.round(Math.random() * limit )]
}
function GetRandomColor() {
    color = '#'
    AddDigitToColor(5)
    for (var i = 0; i < 5; i++) {
        AddDigitToColor(15)
    }
    return color
}

回答by Zaheer Ahmed

As you know RGB at 0,0,0is black the darkest and it goes toward getting light until (255,255,255) so you can stop it to go above 100, to get only dark color or say 9 in hex:

如您所知,RGB at0,0,0是最暗的黑色,并且在 (255,255,255) 之前它会变亮,因此您可以阻止它超过 100,仅获得深色或在十六进制中说 9:

Here is jsFiddle

这是 jsFiddle

function getRandomRolor() {
    var letters = '0123456789'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 10)];
    }
    return color;
}