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 104 105 106 107 108 109 110 111
| const POINTNUM = 70;
let canvas = document.getElementById('particles'), ctx = canvas.getContext('2d'), cwidth = canvas.width = canvas.offsetWidth, cheight = canvas.height = canvas.offsetHeight, circles = [];
window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();
ctx.fillStyle = 'rgba(0, 0, 255, 0.5)'; ctx.strokeStyle = 'rgba(0, 0, 255, 0.1)';
const random = function(start, end) { if (arguments.length < 2) { end = start; start = 1; } return Math.floor(Math.random() * (end - start + 1) + 1); }
class Circle { constructor (x, y) { this.x = x; this.y = y; this.r = random(0.5, 10); this.vx = random(2) - 1.5 || 1; this.vy = random(2) - 1.5 || 1; } drawCircle () { ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 360); ctx.closePath(); ctx.fill(); } drawLine (nextCircle) { let dx = this.x - nextCircle.x, dy = this.y - nextCircle.y, distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 200) { ctx.beginPath(); ctx.moveTo(this.x, this.y); ctx.lineTo(nextCircle.x, nextCircle.y); ctx.closePath(); ctx.stroke(); } } move (w, h) {
if (this.vx > 0) { this.vx = (this.x + this.r < w) ? this.vx: ( - this.vx); } else { this.vx = (this.x < this.r) ? ( - this.vx) : this.vx; } if (this.vy > 0) { this.vy = (this.y + this.r < h) ? this.vy: ( - this.vy); } else { this.vy = (this.y < this.r) ? ( - this.vy) : this.vy; } this.x += this.vx/2; this.y += this.vy/2; } }
const init = () => { for(let i=0; i<POINTNUM; i++) { circles.push(new Circle(random(cwidth), random(cheight))) }
draw(); }
const draw = () => { ctx.clearRect(0, 0, cwidth, cheight); for(let i=0; i<POINTNUM; i++) { circles[i].move(cwidth, cheight); circles[i].drawCircle();
for (let j=i + 1; j<POINTNUM; j++) { circles[i].drawLine(circles[j]); } } requestAnimationFrame(draw); }
window.onload = () => { init(); }
|