const canvas = document.getElementById("particleCanvas");
const ctx = canvas.getContext("2d");

function resizeCanvas() {

    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;

}

window.addEventListener("resize", resizeCanvas);

resizeCanvas();

const particles = [];

const particleCount = 22;

for (let i = 0; i < particleCount; i++) {

    particles.push({

        x: Math.random() * canvas.width,

        y: Math.random() * canvas.height,

        radius: Math.random() * 1.5 + 1,

        dx: (Math.random() - 0.5) * 0.25,

        dy: (Math.random() - 0.5) * 0.25

    });

}

function drawConnections() {

    for (let a = 0; a < particles.length; a++) {

        for (let b = a + 1; b < particles.length; b++) {

            const dx = particles[a].x - particles[b].x;
            const dy = particles[a].y - particles[b].y;

            const distance = Math.sqrt(dx * dx + dy * dy);

            if (distance < 120) {

                const opacity = (120 - distance) / 120 * 0.18;

                ctx.beginPath();

                ctx.moveTo(
                    particles[a].x,
                    particles[a].y
                );

                ctx.lineTo(
                    particles[b].x,
                    particles[b].y
                );

                ctx.strokeStyle =
                    `rgba(200,162,74,${opacity})`;

                ctx.lineWidth = 1;

                ctx.stroke();

            }

        }

    }

}

function animate() {

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    particles.forEach(particle => {

        particle.x += particle.dx;
        particle.y += particle.dy;

        if (particle.x <= 0 || particle.x >= canvas.width)
            particle.dx *= -1;

        if (particle.y <= 0 || particle.y >= canvas.height)
            particle.dy *= -1;

    });

    drawConnections();

    particles.forEach(particle => {

        ctx.beginPath();

        ctx.arc(
            particle.x,
            particle.y,
            particle.radius,
            0,
            Math.PI * 2
        );

        ctx.fillStyle = "rgba(200,162,74,.15)";

        ctx.fill();

    });

    requestAnimationFrame(animate);

}

animate();