Tuesday, February 26, 2013

Create beautiful random color with Javascript


<html>
<head>
</head>
<body>

   <div id="content" />

     <script>
  
      var golden_ratio = 0.618033988749895;
 
      function hsv_to_rgb(h, s, v){
    var r,g,b,p,q,v;
    var hi = (h*6);
var f = h*6 - hi;
p = v * (1  - s);
q = v * (1  - f*s);
t = v * (1  - (1-f) * s);
hi = parseInt(hi,10);
 
if(hi==0) { r=v; g=t; b=p; }
if(hi==1) { r=q; g=v; b=p; }
if(hi==2) { r=p; g=v; b=t; }
if(hi==3) { r=p; g=q; b=v; }
if(hi==4) { r=t; g=p; b=v; }
if(hi==5) { r=v; g=p; b=q; }
return { r : parseInt(r*256,10), g : parseInt(g*256,10), b: parseInt(b*256,10) }
 }
 
 
 var html = '';
 
 var rnd = Math.random();
 var rnds = 0.5;
 var rndv = 0.95;

 for(var i=0;i<6;i++){
 rnd += golden_ratio;
 rnd %= 1;

     var color = hsv_to_rgb(rnd, rnds, rndv);
 var hexString = '#'+color.r.toString(16)+color.g.toString(16)+color.b.toString(16);
 html += '<div style="width:50px;height:50px;background-color: '+hexString+'">&nbsp;</div><br/>';
 }
 
 
 rnds = 0.25;
 rndv = 0.8;
 for(var i=0;i<6;i++){
     console.log('*');
 rnd += golden_ratio;
 rnd %= 1;

     var color = hsv_to_rgb(rnd, rnds, rndv);
 var hexString = '#'+color.r.toString(16)+color.g.toString(16)+color.b.toString(16);
 html += '<div style="width:50px;height:50px;background-color: '+hexString+'">&nbsp;</div><br/>';
 }
 
 rnds = 0.3;
 rndv = 0.99;
 for(var i=0;i<6;i++){
     console.log('*');
 rnd += golden_ratio;
 rnd %= 1;

     var color = hsv_to_rgb(rnd, rnds, rndv);
 var hexString = '#'+color.r.toString(16)+color.g.toString(16)+color.b.toString(16);
 html += '<div style="width:50px;height:50px;background-color: '+hexString+'">&nbsp;</div><br/>';
 }
 
 //console.log(html);
 document.getElementById('content').innerHTML = html;
  </script>

</body>

</html>

No comments: