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:21

Short answer with pad to exact size

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

查看更多
冷夜・残月
3楼-- · 2018-12-31 03:22

Use getRandomColor() in place of "#0000FF":

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}



function setRandomColor() {
  $("#colorpad").css("background-color", getRandomColor());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="colorpad" style="width:300px;height:300px;background-color:#000">

</div>
<button onclick="setRandomColor()">Random Color</button>

查看更多
裙下三千臣
4楼-- · 2018-12-31 03:22
function get_random_color() {
    return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16);
}

http://jsfiddle.net/XmqDz/1/

查看更多
余生请多指教
5楼-- · 2018-12-31 03:23
var color = "#";
for (k = 0; k < 3; k++) {
    color += ("0" + (Math.random()*256|0).toString(16)).substr(-2);
}

A breakdown of how this works:

Math.random()*256 gets a random (floating point) number from 0 to 256 (0 to 255 inclusive)
Example result: 116.15200161933899

Adding the |0 strips off everything after the decimal point.
Ex: 116.15200161933899 -> 116

Using .toString(16) converts this number to hexadecimal (base 16).
Ex: 116 -> 74
Another ex: 228 -> e4

Adding "0" pads it with a zero. This will be important when we get the substring, since our final result must have two characters for each color.
Ex: 74 -> 074
Another ex: 8 -> 08

.substr(-2) gets just the last two characters.
Ex: 074 -> 74
Another ex: 08 -> 08 (if we hadn't added the "0", this would have produced "8" instead of "08")

The for loop runs this loop three times, adding each result to the color string, producing something like this:
#7408e4

查看更多
不流泪的眼
6楼-- · 2018-12-31 03:23

My version:

function RandomColor() {
  var hex = (Math.round(Math.random()*0xffffff)).toString(16);
  while (hex.length < 6) hex = "0" + hex;
  return hex;
}
查看更多
公子世无双
7楼-- · 2018-12-31 03:24
'#'+Math.random().toString(16).slice(-3) // three-numbers format aka #f3c
'#'+Math.random().toString(16).slice(-6) // six-number format aka #abc123
查看更多
登录 后发表回答