#6 - Random Animated Dots Background JS

Date: 2018-04-28 12:00 - JS

Simple random dots background for a website. Note: This is somewhat CPU expensive.

document.addEventListener('DOMContentLoaded', function() {
    var canvas = document.createElement('canvas');
    canvas.style = 'position: absolute; top: 0; left: 0; width: 100vw; height: 100vh; z-index: -1;';
    document.body.appendChild(canvas);
    var ctx = canvas.getContext('2d');

    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    var particles = [];
    var numParticles = 100;
    for (var i = 0; i < numParticles; i++) {
        particles.push([Math.random() * width, Math.random() * height, Math.random() * 1 + 1, Math.random() * 0x3f]);
    }

    function draw() {
        const width = canvas.clientWidth;
        const height = canvas.clientHeight;

        if (canvas.width !== width || canvas.height !== height) {
            canvas.width = width;
            canvas.height = height;
        }

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

        for (var i = 0; i < numParticles; i++) {
            ctx.fillStyle = '#666666' + Math.floor(particles[i][3]).toString(16);
            ctx.beginPath();
            ctx.arc(particles[i][0], particles[i][1], particles[i][2], 0, 7);
            ctx.fill();
            particles[i][3] -= 0.3;
            if (Math.floor(particles[i][3]) === 0) {
                particles[i] = [Math.random() * width, Math.random() * height, Math.random() * 1 + 1, Math.random() * 0x3f + 0x3f];
            }
        }
        window.requestAnimationFrame(draw);
    }

    window.requestAnimationFrame(draw);
});

Previous snippet | Next snippet