【问题标题】:jQuery: generate unique random color that hasn't been used alreadyjQuery:生成尚未使用的唯一随机颜色
【发布时间】:2015-01-12 15:51:30
【问题描述】:

http://jsfiddle.net/8ysuw/

Colors.random = function() {
    var result;
    var count = 0;
    for (var prop in this.names)
        if (Math.random() < 1/++count)
           result = prop;
    return { name: result, rgb: this.names[result]};
};

我想确保调用后不会出现相同的颜色。目前它只会继续生成随机颜色,并且有时会显示相同的颜色。

另外,我需要清除之前使用过的所有颜色,这样整个过程才能从头开始。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:
    Colors.called = {};
    Colors.random = function () {
        var keys   = Object.keys(this.names),
            max    = keys.length,
            called = Object.keys(this.called),
            color  = keys[Math.floor(Math.random() * (max - 0)) + 0];
    
        if (Colors.called[color]) {
            if (max === called.length) {
                Colors.called = {};    
            }
    
            return Colors.random();             
        }
    
        Colors.called[color] = true;
        return { name: color, rgb: this.names[color] };
    };
    

    演示:http://jsfiddle.net/8ysuw/75/

    【讨论】:

      【解决方案2】:

      您可以用所有颜色代码/名称填充一个数组(不确定您需要哪一个)并在返回之前删除选定的元素。

      var colorFactory = (function () {
          var allColors = ["red", "green", "blue"];
          var colorsLeft = allColors.slice(0);
      
          return {
              getRandomColor: function () {
                  if (colorsLeft.length === 0) {
                      return undefined;
                  }
      
                  var index = Math.floor(Math.random() * colorsLeft.length);
                  var color = colorsLeft[index];
                  colorsLeft.splice(index, 1);
                  return color;
              },
              reset: function () {
                  colorsLeft = allColors.slice(0);
              }
          };
      }());
      
      // Usage:
      // Get a random color
      var someColor = colorFactory.getRandomColor();
      
      // Reset: mark all colors as unused
      colorFactory.reset();
      

      【讨论】:

        猜你喜欢
        • 2014-10-08
        • 2011-06-11
        • 2011-07-18
        • 2011-11-07
        • 1970-01-01
        • 2013-04-02
        • 2015-06-15
        • 1970-01-01
        • 2017-01-29
        相关资源
        最近更新 更多