function Circle(x, y) { this.x = x; this.y = y; this.radius = 90; this.color = 'rgba(0, 0, 0, 0)'; this.angle = Math.random() * 180; this.speed = 18; } function Particle(x, y) { this.x = x; this.y = y; this.radius = 2; this.color = '#fff'; this.angle = Math.random() * 360; this.vx = 0; this.vy = 0; this.speed = 5; } Particle.prototype.draw = function(ctx) { ctx.save(); ctx.translate(this.x, this.y); ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(0, 0, this.radius, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ctx.restore(); } var canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), W = canvas.width = window.innerWidth, H = canvas.height = window.innerHeight, particles = [], ball = new Circle(W / 2, H / 2), dist, dx, dy, oldX, oldY; setInterval(function() { ball.angle = Math.random() * 360; }, 800); ball.vx = Math.cos(ball.angle) * ball.speed; ball.vy = Math.sin(ball.angle) * ball.speed; function createParticles() { for (var x = 20; x < W; x += W / 50) { for (var i = 0; i < 70; i++) { var particle = new Particle(x, i * 20); particle.oldX = particle.x; particle.oldY = particle.y; particles.push(particle); } } } createParticles(); function drawParticle (particle) { dx = ball.x - particle.x; dy = ball.y - particle.y; dist = Math.sqrt(dx * dx + dy * dy); if (dist < ball.radius + particle.radius) { particle.vx = Math.sin(particle.angle) * particle.speed; particle.vy = Math.cos(particle.angle) * particle.speed; particle.x += particle.vx; particle.y += particle.vy; } else { particle.x = particle.oldX; particle.y = particle.oldY; } particle.draw(ctx); } function drawBall() { if (ball.x + ball.radius > W) { ball.vx *= -1; } else if (ball.x - ball.radius < 0 ) { ball.vx *= -1; } else if (ball.y + ball.radius > H) { ball.vy *= -1; } else if (ball.y < 0 + ball.radius) { ball.vy *= -1; } ball.x += ball.vx; ball.y += ball.vy; ball.draw(ctx); } (function drawFrame(){ window.requestAnimationFrame(drawFrame, canvas); ctx.fillStyle = '#17293a'; ctx.fillRect(0, 0, W, H); particles.forEach(drawParticle); drawBall(); }());