console
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const TOTOL_NUM = 100;
const points = [];
const randomColor = () => "#" + Math.random().toString(16).slice(-6)
for (let i = 0; i < TOTOL_NUM; i++) {
points.push({
radius: Math.random().toFixed(1) * 10 + 1,
left: Math.floor(Math.random() * 500),
top: Math.floor(Math.random() * 500),
xSpeed: Math.random() + 0.1,
ySpeed: Math.random() + 0.1,
color: randomColor()
})
};
const drawPoints = (points) => {
points.forEach(i => {
ctx.save();
ctx.beginPath();
ctx.fillStyle = i.color;
ctx.arc(i.left, i.top, i.radius, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
});
for (let i = 0; i < TOTOL_NUM; i++) {
for (let j = 0; j < TOTOL_NUM; j++) {
if (i !== j) {
const pointA = points[i];
const pointB = points[j];
if (Math.pow(pointA.top - pointB.top, 2) + Math.pow(pointA.left - pointB.left, 2) < 1600) {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = "gray";
ctx.lineWidth = 0.5;
ctx.moveTo(pointA.left, pointA.top);
ctx.lineTo(pointB.left, pointB.top);
ctx.stroke();
ctx.restore();
}
}
}
}
}
const movePoints = (points) => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
points.forEach(i => {
if (i.left - i.radius <= 0) {
i.xSpeed = Math.abs(i.xSpeed);
}
if (i.left + i.radius >= canvas.width) {
i.xSpeed = -Math.abs(i.xSpeed);
};
if (i.top - i.radius <= 0) {
i.ySpeed = Math.abs(i.ySpeed);
}
if (i.top + i.radius >= canvas.height) {
i.ySpeed = -Math.abs(i.ySpeed);
};
i.left = i.left + i.xSpeed;
i.top = i.top + i.ySpeed;
})
};
const draw = () => {
movePoints(points);
drawPoints(points);
window.requestAnimationFrame(draw);
};
draw();
<canvas id="canvas" width="500" height="500"></canvas>
#canvas {
width: 500px;
height: 500px;
box-shadow: 5px 5px 10px gray;
}