Skip to content

Instantly share code, notes, and snippets.

@codenothing
Created March 17, 2010 08:15
Show Gist options
  • Save codenothing/335018 to your computer and use it in GitHub Desktop.
Save codenothing/335018 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Random Color Generator Revisited</title>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'></script>
<script type='text/javascript' src='random-color-generator-revisited.js'></script>
<script type='text/javascript'>
// Used jQuery because it's just easier that way
jQuery(function($){
var $tbody = $('tbody'), Color = new RandomColorGenerator();
// Creating Color
$('#generate').click(function(){
var loop = parseInt($(this).next('input[type=text]').val(), 10), html = $tbody.html(),
hex, rgb, rows = [], i = -1;
if ( loop < 1 ) {
loop = 0;
}
for ( ; ++i < loop ; ) {
hex = Color.random();
rgb = Color.hex2rgb(hex);
rows.push(
"<tr>",
"<td class='block' bgcolor='"+hex+"'>&nbsp;</td>",
"<td>"+hex+"</td>",
"<td>"+rgb.join(',')+"</td>",
"</tr>"
);
}
$tbody.html( rows.join('') + html );
});
$('#reset').click(function(){
Color.reset();
$tbody.html('');
});
});
</script>
<style type='text/css'>
body { font-size: 10pt; }
table { width: 400px; border: 2px solid black; margin: 5px 3px; }
th {text-align: left;}
td.block { border: 2px solid #989898; }
</style>
</head>
<body>
<!--
Random Color Generator Revisited
March 17, 2010
Corey Hart @ http://www.codenothing.com
-->
<h1>Random Color Generator</h1>
<button id="generate">Generate</button>
<input type='text' size='10' value='1' />
<button id="reset">Reset</button>
<table cellpadding='3' cellspacing='2'>
<thead>
<tr>
<th width='30'>Color</th>
<th>Hex</th>
<th>RGB</th>
</tr>
</thead>
<tbody></tbody>
</table>
</body>
</html>
/*!
* Random Color Generator Revisited
* March 17, 2010
* Corey Hart @ http://www.codenothing.com
*/
var RandomColorGenerator = (function(){
// Generator Initiation Function
function Generator( object ){
var self = this, i;
// Ensure new instances are created
if ( ! self instanceof Generator ) {
return new Generator( object );
}
self.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
self.stack = {};
// Extend over defaults
if ( object && typeof object === 'object' ) {
for ( i in object ) {
if ( object.hasOwnProperty(i) ) {
self.defaults[i] = object[i];
}
}
}
}
// Generator Methods
Generator.prototype = {
// 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 ( 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, l = predef.length, i = -1;
self.stack = {};
if ( l > 0 ) {
for ( ; ++i < l ; ) {
self.stack[ predef[i] ] = self.hex2rgb( predef[i] );
}
}
},
// 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 ){
var self = this;
if ( hex.charAt(0) === '#' ) {
hex = hex.substr(1);
}
// Use the stack if possible to reduce processing
return self.stack && self.stack[ '#' + hex ] ? self.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 )
] : [];
}
};
/* Expose independent helper functions */
Generator.rgb2hex = Generator.prototype.rgb2hex;
Generator.hex2rgb = Generator.prototype.hex2rgb;
/* Expose the Random Color Generator */
return Generator;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment