// RequestAnimFrame: a browser API for getting smooth animations window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })(); function between(min,max) { return Math.floor(Math.random()*(max-min+1)+min); } var canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d"); W = window.innerWidth, H = window.innerHeight, particleCount = 150; canvas.height = H; canvas.width = W; function paintCanvas(){ ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); } paintCanvas(); var colors = ["#10d7af", "#3498db", "#9b59b6", "#f1c40f", "#e74c3c"], particles = []; function Particle(x, y, speedx, speedy){ this.x = x; this.y = y; this.speed = { x: speedx, y: speedy }; this.radius = 5; this.color = colors[between(0,colors.length)]; } Particle.prototype.draw = function(){ ctx.beginPath(); ctx.globalCompositeOperation = 'source-over'; ctx.fillStyle = this.color; ctx.globalAlpha = between(.1, 1); ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2, false); ctx.fill(); ctx.closePath(); } Particle.prototype.move = function(){ this.draw(); this.x += this.speed.x; this.y += this.speed.y; // left wall if(this.x <= this.radius) this.speed.x *= -1; // right wall if(this.x >= canvas.width-this.radius) this.speed.x *= -1; // top wall if(this.y <= this.radius) this.speed.y *= -1; // bottom wall if(this.y >= canvas.height-this.radius) this.speed.y *= -1; for(var i = 0; i < particles.length; i++){ var particle = particles[i], particley = particle.y - this.y, particlex = particle.x - this.x, particler = Math.sqrt(particlex * particlex + particley * particley); if(particler < 200){ ctx.beginPath(); ctx.globalAlpha = (50 - particler) / 200; ctx.lineWidth = 0.1; ctx.moveTo(this.x, this.y); ctx.lineTo(particlex, particley); ctx.strokeStyle = colors[between(0,colors.length)]; ctx.lineCap = "round"; ctx.stroke(); ctx.closePath(); } } } for (var i = 0; i < particleCount; i++){ particles.push(new Particle( between(0, canvas.width), between(0, canvas.height), between(-3, 3), between(-3, 3) )); } (function loop(){ ctx.clearRect(0, 0, canvas.width, canvas.height); //paintCanvas(); for (var i = 0; i < particleCount; i++){ particles[i].move(); } requestAnimFrame(loop); })();