n00*_*ki3 397 javascript random colors
鉴于此功能,我想更换颜色与颜色随机发生器.
document.overlay = GPolyline.fromEncoded({
color: "#0000FF",
weight: 10,
points: encoded_points,
zoomFactor: 32,
levels: encoded_levels,
numLevels: 4
});
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
Ana*_*liy 946
用来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());
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
ZPi*_*DER 247
我怀疑任何事情都会比这更快或更短:
"#"+((1<<24)*Math.random()|0).toString(16)
Run Code Online (Sandbox Code Playgroud)
挑战!
小智 151
这是对这个问题的另一种看法.
我的目标是创造充满活力和鲜明的色彩.为了确保颜色不同,我避免使用随机发生器并从彩虹中选择"均匀间隔"的颜色.
这非常适合在Google地图中创建具有最佳"唯一性"的弹出式标记(即,没有两个标记具有相似的颜色).
function rainbow(numOfSteps, step) {
// This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distinguishable vibrant markers in Google Maps and other apps.
// Adam Cole, 2011-Sept-14
// HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
var r, g, b;
var h = step / numOfSteps;
var i = ~~(h * 6);
var f = h * 6 - i;
var q = 1 - f;
switch(i % 6){
case 0: r = 1; g = f; b = 0; break;
case 1: r = q; g = 1; b = 0; break;
case 2: r = 0; g = 1; b = f; break;
case 3: r = 0; g = q; b = 1; break;
case 4: r = f; g = 0; b = 1; break;
case 5: r = 1; g = 0; b = q; break;
}
var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
return (c);
}
Run Code Online (Sandbox Code Playgroud)
如果您希望查看实际情况,请参阅http://blog.adamcole.ca/2011/11/simple-javascript-rainbow-color.html.
Moh*_*sen 50
谁能打败它?
'#'+Math.random().toString(16).substr(-6);
Run Code Online (Sandbox Code Playgroud)
保证始终工作:http://jsbin.com/OjELIfo/2/edit
基于@eterps注释,如果随机颜色的十六进制表示非常短(0.730224609375=> 0.baf),上面的代码仍然可以生成更短的字符串
此代码应适用于所有情况:
function makeRandomColor(){
var c = '';
while (c.length < 7) {
c += (Math.random()).toString(16).substr(-6).substr(-1)
}
return '#'+c;
}
Run Code Online (Sandbox Code Playgroud)
Als*_*nde 27
不需要十六进制字母的哈希.JavaScript可以自己完成:
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();
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*roi 26
我喜欢这一个: '#' + (Math.random().toString(16) + "000000").substring(2,8)
let*_*nje 25
带亮度控制的随机颜色生成:
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(",") + ")";
}
Run Code Online (Sandbox Code Playgroud)
kig*_*iri 25
您也可以在每个好的浏览器上使用HSL(http://caniuse.com/#feat=css3-colors)
function randomHsl() {
return 'hsla(' + (Math.random() * 360) + ', 100%, 50%, 1)';
}
Run Code Online (Sandbox Code Playgroud)
这将只给你明亮的颜色,你可以玩亮度,饱和度和alpha.
// es6
const randomHsl = () => `hsla(${Math.random() * 360}, 100%, 50%, 1)`
Run Code Online (Sandbox Code Playgroud)
jt3*_*t3k 18
'#'+Math.random().toString(16).slice(-3) // three-numbers format aka #f3c
'#'+Math.random().toString(16).slice(-6) // six-number format aka #abc123
Run Code Online (Sandbox Code Playgroud)
way*_*vin 16
Paul Irish在JavaScript中使用Random Hex Color Code Generator 编写的文章绝对令人惊叹.使用:
'#'+Math.floor(Math.random()*16777215).toString(16);
Run Code Online (Sandbox Code Playgroud)
这是源链接:
http://www.paulirish.com/2009/random-hex-color-code-snippets/
And*_*i R 15
这是@Anatoliy提供的解决方案的一个转折点.
我只需要生成浅色(背景),所以我选择了三个字母(#AAA)格式:
function get_random_color() {
var letters = 'ABCDE'.split('');
var color = '#';
for (var i=0; i<3; i++ ) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
Run Code Online (Sandbox Code Playgroud)
Fun*_*ude 13
使用Google搜索可以很容易地找到它:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
更新后的版本:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
ICo*_*mer 12
如果你是像我这样的菜鸟,对十六进制等无能为力,这可能更直观.
function r() { return Math.floor(Math.random() * 255) }
var color = 'rgb(' + r() + "," + r() + "," + r() + ')';
Run Code Online (Sandbox Code Playgroud)
你只需要得到一个字符串,如 'rgb(255, 123, 220)'
Kam*_*ski 11
始终返回有效的RGB 颜色:
`rgb(${[1,2,3].map(x=>Math.random()*256|0)})`
Run Code Online (Sandbox Code Playgroud)
`rgb(${[1,2,3].map(x=>Math.random()*256|0)})`
Run Code Online (Sandbox Code Playgroud)
Eri*_*ing 10
var color = "#";
for (k = 0; k < 3; k++) {
color += ("0" + (Math.random()*256|0).toString(16)).substr(-2);
}
Run Code Online (Sandbox Code Playgroud)
这是如何工作的细分:
Math.random()*256从0到256(0到255)包含一个随机(浮点)数字
示例结果:116.15200161933899
|0在小数点后添加条带.
例如:116.15200161933899 - > 116
使用.toString(16)将此数字转换为十六进制(基数为16).
例如:116 - > 74
另一个例子:228 - > e4
添加"0"垫为零.当我们得到子字符串时这很重要,因为我们的最终结果必须为每种颜色都有两个字符.
例如:74 - > 074
另一个例子:8 - > 08
.substr(-2)只获取最后两个字符.
例:074 - > 74
另一个例子:08 - > 08(如果我们没有添加"0",这将产生"8"而不是"08")
在for循环运行这个循环三次,将每个结果的颜色字符串,产生这样的:
#7408e4
Kam*_*ski 10
始终返回有效的十六进制 6 位颜色
"#xxxxxx".replace(/x/g, y=>(Math.random()*16|0).toString(16))
Run Code Online (Sandbox Code Playgroud)
"#xxxxxx".replace(/x/g, y=>(Math.random()*16|0).toString(16))
Run Code Online (Sandbox Code Playgroud)
所以虽然这里的所有答案都很好,但我想要对输出进行更多控制.例如,我想要防止任何近乎白色的阴影,同时确保我获得明亮鲜艳的色彩,而不是褪色.
function generateColor(ranges) {
if (!ranges) {
ranges = [
[150,256],
[0, 190],
[0, 30]
];
}
var g = function() {
//select random range and remove
var range = ranges.splice(Math.floor(Math.random()*ranges.length), 1)[0];
//pick a random number from within the range
return Math.floor(Math.random() * (range[1] - range[0])) + range[0];
}
return "rgb(" + g() + "," + g() + "," + g() +")";
};
Run Code Online (Sandbox Code Playgroud)
所以现在我可以指定3个任意范围来从中选择rgb值.您可以在没有参数的情况下调用它并获取我的默认设置,这通常会产生一个非常鲜明的颜色,具有明显的主导色调,或者您可以提供自己的范围数组.
最佳答案的最高投票评论表明Martin Ankerl的方法优于随机十六进制数,虽然我没有改进Ankerl的方法,但我已成功将其翻译为JavaScript.我想我会对这个已经超大的SO线程发布一个额外的答案,因为最顶层的答案有另一个注释链接到一个Gist与Ankerl逻辑的JS实现,并且该链接被破坏(404).如果我有声誉,我会简单地评论我创建的jsbin链接.
// adapted from
// http://jsfiddle.net/Mottie/xcqpF/1/light/
const rgb2hex = (rgb) => {
return (rgb && rgb.length === 3) ? "#" +
("0" + parseInt(rgb[0],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) : '';
}
// next two methods converted from Ruby to JS
// soured from http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
// # HSV values in [0..1[
// # returns [r, g, b] values from 0 to 255
const hsv_to_rgb = (h, s, v) => {
const h_i = Math.floor(h*6)
const f = h*6 - h_i
const p = v * (1 - s)
const q = v * (1 - (f * s))
const t = v * (1 - (1 - f) * s)
let r, g, b
switch(h_i){
case(0):
[r, g, b] = [v, t, p]
break
case(1):
[r, g, b] = [q, v, p]
break
case(2):
[r, g, b] = [p, v, t]
break
case(3):
[r, g, b] = [p, q, v]
break
case(4):
[r, g, b] = [t, p, v]
break
case(5):
[r, g, b] = [v, p, q]
break
}
return [Math.floor(r * 256), Math.floor(g * 256), Math.floor(b * 256)]
}
// # use golden ratio
const golden_ratio_conjugate = 0.618033988749895
let h = Math.random() // # use random start value
const gen_hex = (numberOfColors) => {
const colorArray = []
while (numberOfColors > 0) {
h += golden_ratio_conjugate
h %= 1
colorArray.push(rgb2hex(hsv_to_rgb(h, 0.99, 0.99)))
numberOfColors -= 1
}
console.log(colorArray)
return colorArray
}
gen_hex(100)
Run Code Online (Sandbox Code Playgroud)
https://jsbin.com/qeyevoj/edit?js,console
`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0).slice(-6)}`
Run Code Online (Sandbox Code Playgroud)
`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0)}`
Run Code Online (Sandbox Code Playgroud)
又一个随机颜色发生器:
var randomColor;
randomColor = Math.random() * 0x1000000; // 0 < randomColor < 0x1000000 (randomColor is a float)
randomColor = Math.floor(randomColor); // 0 < randomColor <= 0xFFFFFF (randomColor is an integer)
randomColor = randomColor.toString(16); // hex representation randomColor
randomColor = ("000000" + randomColor).slice(-6); // leading zeros added
randomColor = "#" + randomColor; // # added
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式来完成此任务。这是我做的一些事情:
生成六个随机十六进制数字(0-F)
function randColor() {
for (var i=0, col=''; i<6; i++) {
col += (Math.random()*16|0).toString(16);
}
return '#'+col;
}
Run Code Online (Sandbox Code Playgroud)
极短的单缸
'#'+Math.random().toString(16).slice(-6)
Run Code Online (Sandbox Code Playgroud)
生成单个RGB分量(00-FF)
function randColor2() {
var r = ('0'+(Math.random()*256|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*256|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*256|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
Run Code Online (Sandbox Code Playgroud)
过度设计的十六进制字符串(XOR 3一起输出以形成颜色)
function randColor3() {
var str = Math.random().toString(16) + Math.random().toString(16),
sg = str.replace(/0./g,'').match(/.{1,6}/g),
col = parseInt(sg[0], 16) ^
parseInt(sg[1], 16) ^
parseInt(sg[2], 16);
return '#' + ("000000" + col.toString(16)).slice(-6);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Array.prototype.reduce 使它非常干净.
["r","g","b"].reduce(function(res) {
return res + ("0"+~~(Math.random()*256).toString(16)).slice(-2)
}, "#")
Run Code Online (Sandbox Code Playgroud)
旧浏览器需要垫片.
你可以使用这个简单的功能
function getRandomColor(){
var color = "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
return color;
}
Run Code Online (Sandbox Code Playgroud)
我想创造非常独特和充满活力的颜色(用于绘图)。对于任何严肃的事情,hsl 是比 rgb 更好的方法。如有必要,您可以将 hsl 转换为 rgb,正如其他人已经提到的那样。
color_generator = () => hsl (360*Math.random(), 0.5 + Math.random()/2, 0.5)
Run Code Online (Sandbox Code Playgroud)
它创造了一个非常漂亮的明亮和生动的颜色光谱,但问题是在通常的色谱中,红色、绿色、蓝色色调比黄色、青色和紫色更占主导地位。所以,我通过acos函数转换了色调。技术原因很无聊,所以我跳过它,但你可以在 wiki 中挖掘。
color_generator = () => {
let color_section = Math.floor(Math.random()/0.33) // there are three section in full spectrum
let transformed_hue = Math.acos(2*Math.random() - 1)/3.14 // transform so secondary colors would be as dominant as the primary colors
let hue = 120*color_section + 120*transformed_hue
return hsl(hue, 0.5 + Math.random()/2, 0.5)
}
Run Code Online (Sandbox Code Playgroud)
结果是我在尝试了许多其他方法后获得的最佳色谱。
参考:
小智 5
function get_random_color() {
return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
538286 次 |
| 最近记录: |