function Ball (x, y) { this.x = x; this.y = y; this.radius = 50; this.vx = 10; this.vy = 0; } var canvas = document.querySelector('canvas'), ctx = canvas.getContext('2d'), W = canvas.width = window.innerWidth, H = canvas.height = window.innerHeight, points = { firstRow: [], secondRow: [], thirdRow: [], fourthRow: [], fifthRow: [], sixthRow: [], seventhRow: [] }, ball1 = new Ball(W / 2, H / 2); function generatePoints() { var y; for (var key in points) { if (key === 'firstRow') { y = H / 2 - 150; } else if (key === 'secondRow') { y = H / 2 - 100; } else if (key === 'thirdRow') { y = H / 2 - 50; } else if (key === 'fourthRow') { y = H / 2; } else if (key === 'fifthRow') { y = H / 2 + 50; } else if (key === 'sixthRow') { y = H / 2 + 100; } else if (key === 'seventhRow') { y = H / 2 + 150; } for (x = 50; x < W - 50; x += 40) { points[key].push({ oldX: x, oldY: y, x: x, y: y, vx: 0, vy: 0, px: x - 70, py: y}); } } } generatePoints(100); function movePoints() { ctx.save(); var dx, dy, dist; for (var key in points) { ctx.beginPath(); ctx.moveTo(points[key][0].x, points[key][0].y); points[key].forEach(function (p) { dx = ball1.x - p.x; dy = ball1.y - p.y; dist = Math.sqrt(dx * dx + dy * dy); if (dist < 200) { p.vx = Math.random() * 2 - 1; p.vy = Math.random () * -30; } else if (dist === 200) { p.vx = p.vy = 0; } else if (dist > 200 && dist < 300) { p.vy = Math.random() * -12; } else { p.vx = (p.oldX - p.x) * .1; p.vy = (p.oldY - p.y) * .1; } p.x += p.vx; p.y += p.vy; ctx.strokeStyle = '#fff'; ctx.lineTo(p.x, p.y); }); ctx.stroke(); ctx.closePath() } ctx.restore(); } function moveBall(ball) { if (ball.x >= W - ball.radius / 2) { ball.x = W - ball.radius / 2; ball.vx *= -1; } else if (ball.x < 0 + ball.radius / 2) { ball.x = 0 + ball.radius / 2; ball.vx *= -1; } ball.x += ball.vx; ball.y += ball.vy; } (function drawFrame() { window.requestAnimationFrame(drawFrame, canvas); ctx.fillStyle = '#17293a'; ctx.fillRect(0, 0, W, H); movePoints(); moveBall(ball1); }());