I have this code:
function rand_colorCode(){
$r = dechex(mt_rand(0,255));
$g = dechex(mt_rand(0,255));
$b = dechex(mt_rand(0,255));
$rgb = $r.$g.$b;
if($r == $g && $g == $b){
$rgb = substr($rgb,0,3);
}
return '#'.$rgb;
}
$code = rand_colorCode();
This generates a random color which later gets inserted into the mysql db. But sometimes it generates too light color. (this is a problem because these colors are later displayed and my background color is white)
My simple question is: How can I prevent colors being too light or too dark? How should I customize my code?
Well the RGB code of (for instance) white is 255, 255, 255.
You can just define a rule that if all three values (R, G & B) are above a certain treshold, the color will be too light and will thus not display correctly. Try to define a treshold yourself by having a look at a color palet. Maybe 200, 200, 200 would be the maximum you’d want and 50, 50, 50 the minimum.
You can then just randomize a color from 50 up to 200 (if you define that as your treshold). So instead of
You do
This could be an easy way to fix it.