Advertisement
lalatino

Animated colors

Jul 2nd, 2012
1,582
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html><head>
  2. <script type="text/javascript">
  3. <!--
  4. function animate(id,color0,color1,duration){
  5.     //public attributes
  6.     this.elem = document.getElementById(id);
  7.     //private attributes
  8.     var r0= parseInt(color0.substring(0,2),16);
  9.     var g0= parseInt(color0.substring(2,4),16);
  10.     var b0= parseInt(color0.substring(4,6),16);
  11.     var r1= parseInt(color1.substring(0,2),16);
  12.     var g1= parseInt(color1.substring(2,4),16);
  13.     var b1= parseInt(color1.substring(4,6),16);
  14.     var wait = 100; //100ms
  15.     var steps = duration/wait;
  16.     var rstep = (r1 - r0) / (steps);
  17.     var gstep = (g1 - g0) / (steps);
  18.     var bstep = (b1 - b0) / (steps);
  19.     var self = this;
  20.     //public functions
  21.     this.step  = function() {
  22.         steps--;
  23.         if ( steps>0 ) {
  24.             r0 = Math.floor(r0 + rstep);
  25.             g0 = Math.floor(g0 + gstep);
  26.             b0 = Math.floor(b0 + bstep);
  27.             elem.style.backgroundColor = 'rgb('+r0+','+g0+','+b0+')';
  28.             //alert(steps + ' ; ' + elem.style.backgroundColor);
  29.             window.setTimeout(function(){self.step();}, wait);
  30.             //http://www.west-wind.com/weblog/posts/2006/Mar/28/JavaScript-windowSetTimeout-to-a-JavaScript-Class-method-or-function-with-parameters#5042
  31.             //http://blog.vorpal.cc/category/development/javascript-class-event-handlers.html
  32.         } else {
  33.             elem.style.backgroundColor = '#'+color1;
  34.         }
  35.     }
  36.     step();
  37.     //alert(this.b0);
  38. }
  39. //-->
  40. </script>
  41. </head><body>
  42. <div id="anim" style="width:100px; height:100px; background-color:#ff0000"></div>
  43. <input type="button" onclick="animate('anim','1122ff','ff2211',1000)" value="test" />
  44. </body>
  45. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement