Random color generator

2018-12-31 03:00发布

Given this function, I want to replace the color with a random color generator.

document.overlay = GPolyline.fromEncoded({
    color: "#0000FF",
    weight: 10,
    points: encoded_points,
    zoomFactor: 32,
    levels: encoded_levels,
    numLevels: 4
});

How can I do it?

30条回答
流年柔荑漫光年
2楼-- · 2018-12-31 03:03

There is no need for a hash of hexadecimal letters. JavaScript can do this by itself:

function get_random_color() {
  function c() {
    var hex = Math.floor(Math.random()*256).toString(16);
    return ("0"+String(hex)).substr(-2); // pad with zero
  }
  return "#"+c()+c()+c();
}
查看更多
流年柔荑漫光年
3楼-- · 2018-12-31 03:06

You can also use HSL available on every good browser (http://caniuse.com/#feat=css3-colors)

function randomHsl() {
    return 'hsla(' + (Math.random() * 360) + ', 100%, 50%, 1)';
}

This will give you only bright colors, you can play around with the brightness, saturation and alpha.

// es6
const randomHsl = () => `hsla(${Math.random() * 360}, 100%, 50%, 1)`
查看更多
梦醉为红颜
4楼-- · 2018-12-31 03:07

I doubt anything will be faster or shorter than this one:

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

Challenge!

查看更多
临风纵饮
5楼-- · 2018-12-31 03:08

I like this one: '#' + (Math.random().toString(16) + "000000").substring(2,8)

查看更多
只靠听说
6楼-- · 2018-12-31 03:09

Random color generation with brightness control:

function getRandColor(brightness){

    // Six levels of brightness from 0 to 5, 0 being the darkest
    var rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256];
    var mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5
    var mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x){ return Math.round(x/2.0)})
    return "rgb(" + mixedrgb.join(",") + ")";
}
查看更多
只靠听说
7楼-- · 2018-12-31 03:11

ES6 version.

Random color

`#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, 0)}`

Random alpha, random color.

`#${Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, 0)}`
查看更多
登录 后发表回答