给定这个函数,我想用随机颜色生成器替换颜色。

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

我该怎么做呢?


当前回答

下面是对这个问题的另一种看法。

我的目标是创造充满活力和独特的颜色。为了确保颜色的不同,我避免使用随机生成器,并从彩虹中选择“均匀间隔”的颜色。

这非常适合在谷歌map中创建具有最佳“唯一性”(即没有两个标记具有相似的颜色)的弹出式标记。

/**
 * @param numOfSteps: Total number steps to get color, means total colors
 * @param step: The step number, means the order of the color
 */
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);
}

如果您希望看到这看起来像在行动,请参阅简单JavaScript彩虹颜色生成器谷歌地图标记。

其他回答

投票最多的回答表明,Martin Ankerl的方法比随机十六进制数字更好,尽管我还没有改进Ankerl的方法,但我已经成功地将其翻译成JavaScript。

我想我应该对这个已经非常大的Stack Overflow问题发布一个额外的答案,因为顶部的答案有另一个评论链接到一个带有Ankerl逻辑的JavaScript实现的Gist,而这个链接是坏的(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) : '';
}

// The next two methods are converted from Ruby to JavaScript.
// It is sourced 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 the golden ratio
const golden_ratio_conjugate = 0.618033988749895
let h = Math.random() // # Use a 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)

https://jsbin.com/qeyevoj/edit?js,console

这是我的两个版本的随机十六进制代码生成器。


/* Slowest but shortest. */
"#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});    

/* Good performance with small size. */
"#"+(function(a,b){while(a--){b+=""+(~~(Math.random()*16)).toString(16);} return b;})(6,"");

/* Remy Sharp provided one that's the fastest but a little bit too long */
(function(h){return '#000000'.substr(0,7-h.length)+h})((~~(Math.random()*(1<<24))).toString(16))

function randomColor(format = 'hex') {
    const rnd = Math.random().toString(16).slice(-6);
    if (format === 'hex') {
        return '#' + rnd;
    }
    if (format === 'rgb') {
        const [r, g, b] = rnd.match(/.{2}/g).map(c=>parseInt(c, 16));
        return `rgb(${r}, ${g}, ${b})`;
    }
}

下面是@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;
}

只是因为我可以,我创建了一个不可读的片段,在最小和最大十六进制代码之间随机…:

function a(f, s){
    if(!s || !s.length > 1) return "";
    var c = Math.floor(Math.random()*(parseInt("0x" + s.substr(0,2))-parseInt("0x" +     f.substr(0,2))+1)+parseInt("0x" + f.substr(0,2))).toString(16);
    return  (Array(3 - c.length).join("0")) + c + a(f.substr(2,f.length),s.substr(2,s.length));
}

A ("990099","ff00ff")→可能随机化→b5009e

它是成对的,a("12","f2")→可能随机化→8f。 但它不会超过f2。

var color = "#" + a("11","22") + a("33","44") + a("55","66");

即:

var color = "#" + a("113355","224466")

但速度较慢。