Circle Pack

by soulwire

JavaScript

var canvas = document.createElement( 'canvas' );
canvas.width = canvas.height = 500;

var ctx = canvas.getContext( '2d' );
document.body.appendChild( canvas );

function Dot( color ) {
    this.color = color;
    this.radius = 0;
    this.x = 0;
    this.y = 0;
}

Dot.prototype = {
    draw: function() {
        ctx.beginPath();
        ctx.arc( this.x, this.y, this.radius, 0, Math.PI * 2 );
        ctx.fillStyle = this.color;
        ctx.fill();
    }
};

var a = new Dot( 'red' );
var b = new Dot( 'green' );
var c = new Dot( 'blue' );

function test() {

    canvas.width = canvas.width;

    ctx.save();
    ctx.globalAlpha = 0.8;
    ctx.translate( canvas.width/2, canvas.height/2 );

    a.radius = 10 + Math.random() * 100;
    b.radius = 10 + Math.random() * 100;
    c.radius = 10 + Math.random() * 100;
    
    // layout
    
    var step = Math.PI/1.5;
    
    a.x = Math.cos( step ) * a.radius;
    a.y = Math.sin( step ) * a.radius;
    
    b.x = Math.cos( step*2 ) * b.radius;
    b.y = Math.sin( step*2 ) * b.radius;
    
    c.x = Math.cos( step*3 ) * c.radius;
    c.y = Math.sin( step*3 ) * c.radius;
    
    //

    a.draw();
    b.draw();
    c.draw();
    
    ctx.fillStyle = 'yellow';
    ctx.beginPath();
    ctx.arc( 0, 0, 3, 0, Math.PI * 2 );
    ctx.fill();

    ctx.restore();
}

window.addEventListener( 'click', test );
test();