Javascript-产生随机的深色 [英] Javascript - Generate random dark color

查看:116
本文介绍了Javascript-产生随机的深色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种方法可以为我生成随机的字体颜色:

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

推荐答案

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

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

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;
}

您还可以只使用 hsl (休,饱和度,亮度或亮度). hsl链接实际上经过了上面的代码.

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

这篇关于Javascript-产生随机的深色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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