Friday, June 22, 2007

Vivid random colors

If you want more control over how to create random colors, you need to steer away from the RGB space and go into the more human-friendly HSB color space, which is Hue/Saturation/Brightness.

Unfortunately flash doesn't natively support this but you can convert between the color spaces using some help functions like the following which were found here:

function hsv2rgb(hue, sat, val) {
var red, grn, blu, i, f, p, q, t;
if(val==0) {return({r:0, g:0, v:0});}
i = Math.floor(hue);
f = hue-i;
p = val*(1-sat);
q = val*(1-(sat*f));
t = val*(1-(sat*(1-f)));
if (i==0) {red=val; grn=t; blu=p;}
else if (i==1) {red=q; grn=val; blu=p;}
else if (i==2) {red=p; grn=val; blu=t;}
else if (i==3) {red=p; grn=q; blu=val;}
else if (i==4) {red=t; grn=p; blu=val;}
else if (i==5) {red=val; grn=p; blu=q;}
red = Math.floor(red*255);
grn = Math.floor(grn*255);
blu = Math.floor(blu*255);
return ({r:red, g:grn, b:blu});
function rgb2hsv(red, grn, blu) {
var x, val, f, i, hue, sat, val;
x = Math.min(Math.min(red, grn), blu);
val = Math.max(Math.max(red, grn), blu);
if (x==val){
return({h:undefined, s:0, v:val*100});
f = (red == x) ? grn-blu : ((grn == x) ? blu-red : red-grn);
i = (red == x) ? 3 : ((grn == x) ? 5 : 1);
hue = Math.floor((i-f/(val-x))*60)%360;
sat = Math.floor(((val-x)/val)*100);
val = Math.floor(val*100);
return({h:hue, s:sat, v:val});
So to create vivid random colors you just randomize the Hue, and set a high Saturation and Brightness. If you just want random shades of a color, you set the Hue and Saturation and just randomize the Brightness.


Gaurav said...

Your game doesn't work, fix that first

TV de LCD said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the TV de LCD, I hope you enjoy. The address is A hug.