Javascript Random Color Generator
December 28, 2009 | Download
The Random Color Generator not only randomly creates colors, it also stores those colors so they are not repeated in the next request.
UsageThe generator takes up a single namespace, Color, with a defaults object extension attached to it. Those defaults are defined below.
- predef: An array of hex values (prefixed with the '#' symbol) that cannot be used by the generator.
- randMax: Highest number that the rand method can obtain. Defaults to 255.
- randMin: Lowest number the the rand method can obtain. Defaults to 0.
- levelUp: Upper level that one of the rgb values must pass to be valid. Defaults to -1 (to include all values).
- levelDown: Lower level that one of the rgb values must pass to be valid. Defaults to 256 (to include all values).
- recursionLimit: Number of loops the generator can call upon itself before failing (to prevent recursion errors). Defaults to 15.
- recursion: Callback function for when the recursionLimit is reached. Default function throws an error.
The generator uses a few methods internally that have been exposed as they may be useful.
- random: Returns a non-duplicate hex value.
- rand: Returns a random integer between the randMin and randMax default values.
- reset: Clears the stack cache, and resets the generator to start from scratch.
- rgb2hex: Converts rgb values into hex code form. Takes three parameters, (red, green blue).
- hex2rgb: Converts a hex code string into rgb values. Returns in array form [red, green, blue].
| Color | Hex | RGB |
|---|
The source package includes a demo page that uses jQuery as a helper. The generator itself is framework independent.
/*!
* Random Color Generator
* December 28, 2009
* Corey Hart @ http://www.codenothing.com
*/
var Color = {
defaults: {
// Predefined hex codes that cant be used as random colors
// All must be prefixed with the '#' indicator
predef: [],
// Maximum & Minimum random range values
rangeMax: 255,
rangeMin: 0,
// Upper and lower level values that must be
// passed for random color acceptance
//
// By setting levelUp: 200, levelDown: 100; Neutral
// colors like White, Gray, and Black can be somewhat weeded
// out and your random colors will be full spectrum based.
// Note*: Doing so increases likely hood of recursion
levelUp: -1,
levelDown: 256,
// Recursion handlers
recursionLimit: 15,
recursion: function(){
throw 'Recursion Error in Random Color Generator, ' +
'too many tries on finding random color, ' +
'[Limit ' + this.recursionLimit + ']';
}
},
// Caching of random colors
stack: {},
// Returns a random color in hex code form, and caches
// find in the stack.
random: function(i){
var self = this,
defaults = self.defaults,
r = self.rand(),
g = self.rand(),
b = self.rand(),
hex = self.rgb2hex(r, g, b),
levels = true;
// Check for recursion
if (i === undefined || typeof i !== 'number') i = 0;
else if (i++ > defaults.recursionLimit) return defaults.recursion();
// Color already used, try another one
if (self.stack[hex]) hex = self.random(i);
// Ensure one of the vals is above levelUp and another is below levelDown
// Check defaults comments for better understanding
levels = !!(
(r > defaults.levelUp || g > defaults.levelUp || b > defaults.levelUp) &&
(r < defaults.levelDown || g < defaults.levelDown || b < defaults.levelDown)
);
if (! levels) hex = self.random(i);
// Store on stack to help prevent repeat
self.stack[hex] = [r,g,b];
// Return hex code in #
return hex;
},
// Returns random number within range
rand: function(){
var defaults = this.defaults;
return defaults.rangeMin + Math.floor(Math.random()*(defaults.rangeMax+1));
},
// Clears the stack
reset: function(){
var self = this,
predef = self.defaults.predef,
i = -1, l = predef.length;
self.stack = {};
if (l > 0)
for ( ; ++i < l; )
self.stack[ predef[i] ] = true;
},
// Returns hex code
rgb2hex: function(r, g, b){
var str = '0123456789ABCDEF';
return '#' + [
str.charAt((r-r%16)/16) + str.charAt(r%16),
str.charAt((g-g%16)/16) + str.charAt(g%16),
str.charAt((b-b%16)/16) + str.charAt(b%16)
].join('');
},
// Returns in array form [red, green, blue]
hex2rgb: function(hex){
if (hex.substr(0, 1) === '#')
hex = hex.substr(1);
// Use the stack if possible to reduce processing
return this.stack['#'+hex] ? this.stack['#'+hex] :
hex.length === 6 ? [
parseInt(hex.substr(0, 2), 16),
parseInt(hex.substr(2, 2), 16),
parseInt(hex.substr(4, 2), 16)
] : hex.length === 3 ? [
parseInt(hex.substr(0, 1), 16),
parseInt(hex.substr(1, 1), 16),
parseInt(hex.substr(2, 1), 16)
] : [];
}
};
Download
Latest: javascript-random-color-generator.zipReleased: December 28, 2009
-Initial Release
Have a question or comment? ask@codenothing.com.
RSS