Friday, June 20, 2008

Random Color Generation With Javascript

I'm sure there's quite a few ways to get a random color using JS, I can think of a few such as returning a random index from an array of CSS color names, or generating three random numbers between zero and 255 and formatting from there.

The following method is my favorite though because the single randomly generated integer can be easily converted into pretty much any other format or quickly returned as-is.
To illustrate this I've written the following function which will return a hexidecimal, RGB, or integer format random color depending on the argument passed to the function.

// @format (hex|rgb|null) : Format to return, default is integer
function random_color(format)
{
var rint = Math.round(0xffffff * Math.random());
switch(format)
{
case 'hex':
return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
break;

case 'rgb':
return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
break;

default:
return rint;
break;
}
}

6 comments:

Anonymous said...

Better random_color, in hex:

Math.round(0xffffff * Math.random()).toString(16);

Anonymous said...

Amazing. Concise and functional. Thanks!

Anonymous said...

There's a bug in the code in that comment from '09, it wont always return 6 digits, here's a nicer one that will:

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

also, how is that buggy code "better"? just because it's shorter? i'm sure the OP code is valid(which is better than invalid no matter how lengthy), but haven't tried it though heh

wootapa said...

Well, assuming not buggy, whats not to like with short and concise? Its clearly more elegant and more readable!

'#'+Math.floor(Math.random()*16777215).toString(16);

Gautham Manivannan said...

return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';

i can't understand this line. can anyone please explain it?

Joe Kovar said...

Gautham, the overall purpose of that line is to generate a color string that can be used with CSS. Something along the lines of "rgb(12,34,56)".

A term to search for, which will return results that make the "rint >> 16" parts easier to understand is "bitshifting".

The "rint & 255" can be explained by results for "binary and", or "bitmask".