Javascript - Generate random dark color

别来无恙 提交于 2020-04-09 18:04:52

问题


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


回答1:


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

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




回答2:


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

JS Fiddle: 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
}



回答3:


As you know RGB at 0,0,0 is 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:

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


来源:https://stackoverflow.com/questions/20114469/javascript-generate-random-dark-color

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!