Run Save Upload File Fullscreen About

			
body {
    margin: 0;
    padding: 0;
    overflow: hidden;
}
// Number of circles
var n = 100;
// Size (radius)
var size = 25;
// Desired frames per second
var fps = 60;
// Speed (arbitrary)
var speed = 5;

// Create canvas
var canvas = document.createElement( 'canvas' );
canvas.style.position = 'absolute';
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.id = "myCanvas";
document.body.appendChild( canvas );
var context = canvas.getContext( '2d' );

// Create circles
var circles = [];
for (var i = 0; i < n; i++) {
    circles[i] = {x : (Math.random()*(window.innerWidth-(2*size))+size),
                    y : (Math.random()*(window.innerHeight-(2*size))+size),
                    id : i,
                    vX : ((Math.random()*10)-5)*(speed/(fps/10)), // FPS does not modify the balls speed
                    vY : ((Math.random()*10)-5)*(speed/(fps/10)),
                    radius : size,
                    color : getRandomColor()};
}

// Frames drawed
var framesDrawn = 0;

// Main loop
setInterval(function() {
    update(circles);
    draw(circles);
    framesDrawn++;
}, 1000/fps);

// Each seconds to count real FPS
setInterval(function() {
    console.clear();
    console.log("FPS : " + framesDrawn);
    framesDrawn = 0;
}, 1000);

// Update circles position
function update(circles) {
    for (var i = 0; i < circles.length; i++) {
        // Update position
        circles[i].x += circles[i].vX;
        circles[i].y += circles[i].vY;
        // Check for border collision
        if (circles[i].x <= circles[i].radius) {
            circles[i].x = circles[i].radius;
            circles[i].vX *= -1;
        } else if (circles[i].y <= circles[i].radius) {
            circles[i].y = circles[i].radius;
            circles[i].vY *= -1;
        } else if (circles[i].x >= canvas.width-circles[i].radius) {
            circles[i].x = canvas.width-circles[i].radius;
            circles[i].vX *= -1;
        } else if (circles[i].y >= canvas.height-circles[i].radius) {
            circles[i].y = canvas.height-circles[i].radius;
            circles[i].vY *= -1;
        }
    }
}

// Draw the circles
function draw(circles) {
    context.clearRect(0, 0, canvas.width, canvas.height);
    for (var i = 0; i < circles.length; i++) {
        context.beginPath();
        context.arc(circles[i].x, circles[i].y, circles[i].radius, 0, 2*Math.PI);
        context.fillStyle = circles[i].color;
        context.fill();
        context.closePath();
    }
}

// Return a random color (in a list)
function getRandomColor() {
    var colors = ["#1dd2af", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60",
    "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6",
    "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];
    return colors[Math.floor(Math.random() * colors.length)]
}
JavaScript Console