add ball

by ostapische

HTML

<button onclick="generateBall();">Add circle</button>

CSS

body {
    position: relative;
}

JavaScript

function addBall( ball, parent, isImage ) {
    var el = document.createElement( "div" );
    el.style.width = ( ball.radius * 2 ) + "px";
    el.style.height = ( ball.radius * 2 ) + "px";
    el.style.position = "absolute";
    el.style.left = ball.left + "px";
    el.style.top = ball.top + "px";
    if ( isImage ) {
        el.style.background = "url( " + ball.image + " ) left top no-repeat";
        el.style.backgroundSize = "cover";
    } else {
        el.style.backgroundColor = ball.fill_color;
    }
    el.style.border = ball.border + "px solid " + ball.border_color;
    el.style.borderRadius = ( ball.border + ball.radius ) + "px";
    el.zIndex = "2";
    parent.appendChild( el );
    var log = document.createElement( "div" );
    log.innerText = JSON.stringify( ball );
    document.body.appendChild( log );
}
var colors = [ "red", "green", "yellow", "blue", "black" ];
var images = [ "http://upload.wikimedia.org/wikipedia/fr/9/9e/Google_Chrome_logo.png", "http://upload.wikimedia.org/wikipedia/cv/0/0c/Firefox-logo.png", "http://upload.wikimedia.org/wikipedia/commons/d/d4/Opera_browser_logo_2013.png", "http://upload.wikimedia.org/wikipedia/en/6/61/Apple_Safari.png" ];
function generateBall() {
    var radius = Math.round( Math.random() * 19 ) + 1;// 1 - 20
    var left = Math.round( Math.random() * 400 );// 0 - 400
    var top = Math.round( Math.random() * 400 );// 0 - 400
    var fill_color = colors[ Math.round( Math.random() * ( colors.length - 1 ) ) ];
    var border = Math.round( Math.random() * 9 ) + 1;// 1 - 10
    var border_color = colors[ Math.round( Math.random() * ( colors.length - 1 ) ) ];
    var image = images[ Math.round( Math.random() * ( images.length - 1 ) ) ];
    addBall( { radius: radius, left: left, top: top, fill_color: fill_color, border: border, border_color: border_color, image: image }, document.body, true );
}