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
| const cvs = document.querySelector("canvas"); const ctx = cvs.getContext("2d");
function init() { cvs.width = window.innerWidth * devicePixelRatio; cvs.height = window.innerHeight * devicePixelRatio; } init();
function getRandom(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
class Point { constructor() { this.r = 6; this.x = getRandom(0, cvs.width - this.r / 2); this.y = getRandom(0, cvs.height - this.r / 2); this.xSpeed = getRandom(-50, 50); this.ySpeed = getRandom(-50, 50); this.lastDrawTime = null; } draw() { if (this.lastDrawTime) { const now = Date.now(); const t = (now - this.lastDrawTime) / 1000; let x = this.x + this.xSpeed * t; let y = this.y + this.ySpeed * t; if (x <= this.r || x >= cvs.width - this.r) { this.xSpeed *= -1; } if (y <= this.r || y >= cvs.height - this.r) { this.ySpeed *= -1; } this.x = x; this.y = y; } ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fillStyle = "rgb(200,200,200)"; ctx.fill(); this.lastDrawTime = Date.now(); } }
class Graph { constructor(pointNumber = 30, maxDis = 500) { this.points = new Array(pointNumber).fill(0).map(() => new Point()); this.maxDis = maxDis; } draw() { requestAnimationFrame(() => { this.draw(); }); ctx.clearRect(0, 0, cvs.width, cvs.height); for (let i = 0; i < this.points.length; i++) { const p1 = this.points[i]; p1.draw(); for (let j = i + 1; j < this.points.length; j++) { const p2 = this.points[j]; const d = Math.sqrt((p2.x - p1.x) ** 2, (p2.y - p1.y) ** 2); if (d > this.maxDis) { continue; } ctx.beginPath(); ctx.moveTo(p1.x, p1.y); ctx.lineTo(p2.x, p2.y); ctx.closePath(); ctx.strokeStyle = `rgba(200,200,200,${this.maxDis})`; ctx.stroke(); } } } }
const g = new Graph(); g.draw();
|