给定这个函数,我想用随机颜色生成器替换颜色。
document.overlay = GPolyline.fromEncoded({
color: "#0000FF",
weight: 10,
points: encoded_points,
zoomFactor: 32,
levels: encoded_levels,
numLevels: 4
});
我该怎么做呢?
给定这个函数,我想用随机颜色生成器替换颜色。
document.overlay = GPolyline.fromEncoded({
color: "#0000FF",
weight: 10,
points: encoded_points,
zoomFactor: 32,
levels: encoded_levels,
numLevels: 4
});
我该怎么做呢?
当前回答
这段代码(Mohsen的)不能生成像#fcfc80这样的颜色。
'#' + Math.random().toString(16).substr(-6);
Nicolas Buduroi的方法有效,除非Math.random()返回0,合理。
'#' + (Math.random().toString(16) + "000000").substring(2,8)
这段代码生成了很多非法的颜色(比如#abcde)。
'#' + Math.floor(Math.random()*16777215).toString(16);
我一直在用(+1或其他也可以,但我习惯了毫无理由的+2)
"#" + ((Math.random()+2)*16777216|0).toString(16).slice(1)
其他回答
这段代码(Mohsen的)不能生成像#fcfc80这样的颜色。
'#' + Math.random().toString(16).substr(-6);
Nicolas Buduroi的方法有效,除非Math.random()返回0,合理。
'#' + (Math.random().toString(16) + "000000").substring(2,8)
这段代码生成了很多非法的颜色(比如#abcde)。
'#' + Math.floor(Math.random()*16777215).toString(16);
我一直在用(+1或其他也可以,但我习惯了毫无理由的+2)
"#" + ((Math.random()+2)*16777216|0).toString(16).slice(1)
正则表达式
总是返回有效的十六进制6位颜色
"#xxxxxx".replace(/x/g, y=>(Math.random()*16|0).toString(16))
令c= "#xxxxxx"。替换(/ x / g, y = > (math . random () * 16 | 0) .toString (16)); console.log (c); document.body.style.background = c
map
总是返回一个有效的RGB颜色:
`rgb(${[1,2,3].map(x=>Math.random()*256|0)})`
让c =“rgb ($ {[1, 2, 3] . map (x = > math . random() * 256 | 0)})” console.log (c); document.body.style.background = c
使用getRandomColor()代替“#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>
Use:
function random_color(format)
{
var rint = Math.round(0xffffff * Math.random());
switch(format)
{
case 'hex':
return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
break;
case 'rgb':
return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
break;
default:
return rint;
break;
}
}
升级版:
function random_color( format ){
var rint = Math.floor( 0x100000000 * Math.random());
switch( format ){
case 'hex':
return '#' + ('00000' + rint.toString(16)).slice(-6).toUpperCase();
case 'hexa':
return '#' + ('0000000' + rint.toString(16)).slice(-8).toUpperCase();
case 'rgb':
return 'rgb(' + (rint & 255) + ',' + (rint >> 8 & 255) + ',' + (rint >> 16 & 255) + ')';
case 'rgba':
return 'rgba(' + (rint & 255) + ',' + (rint >> 8 & 255) + ',' + (rint >> 16 & 255) + ',' + (rint >> 24 & 255)/255 + ')';
default:
return rint;
}
}