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:
Better random_color, in hex:
Math.round(0xffffff * Math.random()).toString(16);
Amazing. Concise and functional. Thanks!
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
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);
return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
i can't understand this line. can anyone please explain it?
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".
Post a Comment