jQuery:生成尚未使用的唯一随机颜色

jQuery: generate unique random color that hasn't been used already

本文关键字:唯一 随机 颜色 未使用 jQuery      更新时间:2023-09-26

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]};
};

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

此外,我需要清除以前使用过的所有颜色,以便整个过程可以从头开始。

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/

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

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();