// From Paul Irish' post: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ // shim layer with setTimeout fallback window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); /* VARS ----------------------------------------------- */ var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'), dots = [], width, height, centerY, centerX, dotsNum = 50, timer = 0, TWO_PI = 2 * Math.PI, colors = [ ['red', 176, 52, 229], ['red', 229, 52, 202], ['red', 216, 229, 0], ['green', 0, 119, 229], ['blue', 0, 229, 145], ['blue', 229, 81, 0] ], colorsLen = colors.length - 1; function Dot(i) { dots[i] = this; this.i = i; this.velocity = 1; this.x = centerX; this.y = centerY; this.radius = 20; this.ranVelocity = (Math.random() * 5 + 1); this.ranColor = Math.round(Math.random() * colorsLen); } function updateColors(selectedColor, increment) { var red = selectedColor[1], green = selectedColor[2], blue = selectedColor[3]; if(selectedColor[0] === 'red') { red = increment; } else if(selectedColor[0] === 'green') { green = increment; } else if(selectedColor[0] === 'blue') { blue = increment; } return 'rgba(' + red + ', ' + green + ', ' + blue + ', 1)'; } Dot.prototype.draw = function() { this.velocity += this.ranVelocity; colorIncrement = 255 - Math.round(this.velocity * (255/(height + this.radius))); ctx.fillStyle = updateColors(colors[this.ranColor], colorIncrement); if(this.velocity >= height + this.radius) { colorIncrement = 255; this.velocity = 0; this.ranColor = Math.round(Math.random() * colorsLen); this.ranVelocity = (Math.random() * 5 + 1); } this.y = -this.radius + this.velocity; this.x = this.radius + (this.i * this.radius * 2); ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, TWO_PI, false); ctx.fill(); } function createDot() { for(var i = 0; i < dotsNum; i++) { new Dot(i); } } /* WINDOW SIZE ----------------------------------------------- */ function canvasSize() { width = window.innerWidth; height = window.innerHeight; centerY = height / 2; centerX = width / 2; canvas.height = height; canvas.width = width; } window.onresize = function(event) { canvasSize(); }; /* RAF LOOP ----------------------------------------------- */ function draw() { requestAnimFrame(draw); // Draw function for(var i in dots) { dots[i].draw(); } }; /* INIT ----------------------------------------------- */ canvasSize(); createDot(); draw();