1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| const canvas = document.getElementById("myCanvas"); canvas.width = document.documentElement.clientWidth; canvas.height = document.documentElement.clientHeight; const ctx = canvas.getContext("2d");
function Ball() { this.x = randomNum(3, canvas.width - 3); this.y = randomNum(3, canvas.height - 3); this.r = randomNum(1, 3); this.color = "rgb(0,0,0)"; this.speedX = randomNum(-3, 3) * 0.6; this.speedY = randomNum(-3, 3) * 0.6; }
Ball.prototype = { draw: function() { ctx.beginPath(); ctx.globalAlpha = 0.4; ctx.fillStyle = this.color; ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fill(); }, move: function() { this.x += this.speedX; this.y += this.speedY; if (this.x <= 3 || this.x > canvas.width - 3) { this.speedX *= -1; } if (this.y <= 3 || this.y >= canvas.height - 3) { this.speedY *= -1; } } };
const balls = [];
const n = 150; for (let i = 0; i < n; i++) { const ball = new Ball(); balls.push(ball); }
main(); function main() { if(canvas.width > 1000){ let step = (timestamp, elapsed) => { if (elapsed > 1000 / 30) { ctx.clearRect(0, 0, canvas.width, canvas.height); drawLine(); elapsed = 0 }
window.requestAnimationFrame( _timestamp => step(_timestamp, elapsed + _timestamp - timestamp) ) }; window.requestAnimationFrame(timestamp => step(timestamp, 0)) } }
let mouseX; let mouseY; canvas.onmousemove = function(e) { const ev = event || e; mouseX = ev.offsetX; mouseY = ev.offsetY; };
function drawLine() { let distance; for (let i = 0; i < balls.length; i++) { balls[i].draw(); balls[i].move(); for (let j = 0; j < balls.length; j++) { if (i !== j) { distance = Math.sqrt(Math.pow((balls[i].x - balls[j].x), 2) + Math.pow((balls[i].y - balls[j].y), 2)); if (distance < 130) { ctx.beginPath(); ctx.moveTo(balls[i].x, balls[i].y); ctx.lineTo(balls[j].x, balls[j].y); ctx.strokeStyle = "rgba(0,0,0," + (1 - distance / 130) + ")"; ctx.stroke(); } } } } }
function randomNum(m, n) { return Math.floor(Math.random() * (n - m + 1) + m); }
|