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

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

我该怎么做呢?


当前回答

我已经生成了100种不同对比度的不同颜色,你可以根据需要增加数值:

Feedle举例:http://jsfiddle.net/zFbfE/29/ -

// CHANGE THE INITIAL SEED HERE
Math.seed = 23;

/**
 * Math.seededRandom()
 *
 */
Math.seededRandom = function(max, min) {
    max = max || 1;
    min = min || 0;

    Math.seed = (Math.seed * 9301 + 49297) % 233280;
    var rnd = Math.seed / 233280.0;

    return min + rnd * (max - min);
}

var c, r = 0,
    l = 100000,
    t,
    random = [],
    seededRandom = [];

for(var i=0; i<100; i++)
{
    random[i] = 0;
    seededRandom[i] = 0;
}

// Do some loops withouth benchmarking
// to have a "fair" comparison
/*for (c = 0; c < l; ++c) {
    r = 5+5;
}*/


// benchmark Math.random()
t = new Date().getTime();
s = '';


// benchmark Math.seededRandom()
t = new Date().getTime();
while(l--){
    r = Math.seededRandom();
    seededRandom[(r*100)|0] += 1;
}

var inc = 0;
for(c=0; c<seededRandom.length; c++) {
    //var inc=15;
    for(var i=0; i<seededRandom.length; i++)
    {
        if(i!==c) {
            if(seededRandom[c] == seededRandom[i]) {
            seededRandom[c] += inc;
            inc = inc + 10;
              //    console.log(seededRandom[c]);
            }
        }
    }
    inc = inc > 255 ? 0 : inc;
}

var a=[], b=[], d=[], inc=0, dec=255;
for(c=0; c<seededRandom.length; c++) {
    a[c] = (seededRandom[c] % 100) + inc;
    b[c] = dec - Math.floor(seededRandom[c]/100);
    if(b[c] < 0)
        b[c] = b[c]* - 1;
    if(a[c] > 255)
        a[c] -= 255;
    d[c] = Math.floor(b[c]/2);
    inc += 5;
    dec -= 5;
}


var app = angular.module("myAppp", []).controller('myCtrl',function($scope, $http) {
$scope.id = [];
for(var i=0; i<seededRandom.length; i++)
    $scope.id.push(i);

// Generate random number
$scope.Icon = [];$scope.Icon2 = [], $scope.Icon3 = [];

var ran = 0, inc = 5, dec = 255;
for(var i=0;i<seededRandom.length;i++)
{
    $scope.Icon.push(a[i]%100);
    $scope.Icon2.push(b[i]%100);
    $scope.Icon3.push(d[i]%100);
    console.log(a[i] + "|" + b[i] + "|" + d[i]);
}

});

它对我有用,我想它对你也会有帮助。

这个例子中最好的一点是,它将生成100个随机颜色,并且每个页面加载的颜色都是相同的。

其他回答

我认为第一个回答是最简洁/有用的,但我只是写了一个初学者可能更容易理解的回答。

function randomHexColor(){
    var hexColor=[]; //new Array()
    hexColor[0] = "#"; //first value of array needs to be hash tag for hex color val, could also prepend this later

    for (i = 1; i < 7; i++)
    {
        var x = Math.floor((Math.random()*16)); //Tricky: Hex has 16 numbers, but 0 is one of them

        if (x >=10 && x <= 15) //hex:0123456789ABCDEF, this takes care of last 6 
        {
            switch(x)
            {
                case 10: x="a" 
                break;
                case 11: x="b" 
                break;
                case 12: x="c" 
                break;
                case 13: x="d" 
                break;
                case 14: x="e" 
                break;
                case 15: x="f" 
                break;  
            }
        }
        hexColor[i] = x;
    }
    var cString = hexColor.join(""); //this argument for join method ensures there will be no separation with a comma
    return cString;
}

有多种方法来创建随机十六进制颜色代码在博客文章中随机十六进制颜色代码生成器在JavaScript。当随机值小于0×100000时,你需要用0填充,所以下面是正确的版本:

var randomColor = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});

这将用一个随机的十六进制数字替换六个0中的每一个,因此它一定会得到一个完整的六位数有效颜色值。

几乎所有以前的速记方法都会生成无效的十六进制代码(五位数)。我在这里遇到了一个类似的技巧,只是没有这个问题:

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

Test

在控制台试试这个:

for(i = 0; i < 200; i++) {
    console.log("#"+(((1+Math.random())*(1<<24)|0).toString(16)).substr(-6));
}

谁能打败它?

'#' + Math.random().toString(16).substr(-6);

它保证一直工作: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;
}

这个函数在两个方面超越了其他答案:

它试图生成尽可能不同的颜色 20种颜色中哪一种与欧几里得距离最远 其他的都在HSV锥内。

它允许你限制色调, 饱和度,或值范围,但它仍然试图选择颜色作为 在这个范围内尽可能的不同。

它不是超级高效,但对于合理的值(谁甚至可以轻松地区分100种颜色?)够快了。

请参阅 JSFiddle

  /**
   * Generates a random palette of HSV colors.  Attempts to pick colors
   * that are as distinct as possible within the desired HSV range.
   *
   * @param {number}    [options.numColors=10] - the number of colors to generate
   * @param {number[]}  [options.hRange=[0,1]] - the maximum range for generated hue
   * @param {number[]}  [options.sRange=[0,1]] - the maximum range for generated saturation
   * @param {number[]}  [options.vRange=[0,1]] - the maximum range for generated value
   * @param {number[][]}[options.exclude=[[0,0,0],[0,0,1]]] - colors to exclude
   *
   * @returns {number[][]} an array of HSV colors (each HSV color
   * is a [hue, saturation, value] array)
   */
  function randomHSVPalette(options) {
    function random(min, max) {
      return min + Math.random() * (max - min);
    }

    function HSVtoXYZ(hsv) {
      var h = hsv[0];
      var s = hsv[1];
      var v = hsv[2];
      var angle = h * Math.PI * 2;
      return [Math.sin(angle) * s * v,
              Math.cos(angle) * s * v,
              v];
    }

    function distSq(a, b) {
      var dx = a[0] - b[0];
      var dy = a[1] - b[1];
      var dz = a[2] - b[2];
      return dx * dx + dy * dy + dz * dz;
    }

    if (!options) {
      options = {};
    }

    var numColors = options.numColors || 10;
    var hRange = options.hRange || [0, 1];
    var sRange = options.sRange || [0, 1];
    var vRange = options.vRange || [0, 1];
    var exclude = options.exclude || [[0, 0, 0], [0, 0, 1]];

    var points = exclude.map(HSVtoXYZ);
    var result = [];

    while (result.length < numColors) {
      var bestHSV;
      var bestXYZ;
      var bestDist = 0;
      for (var i = 0; i < 20; i++) {
        var hsv = [random(hRange[0], hRange[1]), random(sRange[0], sRange[1]), random(vRange[0], vRange[1])];
        var xyz = HSVtoXYZ(hsv);
        var minDist = 10;
        points.forEach(function(point) {
          minDist = Math.min(minDist, distSq(xyz, point));
        });
        if (minDist > bestDist) {
          bestHSV = hsv;
          bestXYZ = xyz;
          bestDist = minDist;
        }
      }
      points.push(bestXYZ);
      result.push(bestHSV);
    }

    return result;
  }

  function HSVtoRGB(hsv) {
    var h = hsv[0];
    var s = hsv[1];
    var v = hsv[2];

    var i = ~~(h * 6);
    var f = h * 6 - i;
    var p = v * (1 - s);
    var q = v * (1 - f * s);
    var t = v * (1 - (1 - f) * s);
    v = ~~(255 * v);
    p = ~~(255 * p);
    q = ~~(255 * q);
    t = ~~(255 * t);
    switch (i % 6) {
      case 0: return [v, t, p];
      case 1: return [q, v, p];
      case 2: return [p, v, t];
      case 3: return [p, q, v];
      case 4: return [t, p, v];
      case 5: return [v, p, q];
    }
  }

  function RGBtoCSS(rgb) {
    var r = rgb[0];
    var g = rgb[1];
    var b = rgb[2];
    var rgb = (r << 16) + (g << 8) + b;
    return '#' + ('000000' + rgb.toString(16)).slice(-6);
  }