Xroad
Xroad

Reputation: 425

Random circles with jQuery

I didn't manage to find a jQuery plugin that permit to create random circles like this :

Can you help me please ?

.circle {
    border-radius: 50%;
    width: 200px;
    height: 200px; 
}

.circle .blue {
    background-color: #00c0f1;
}

.circle .green {
    background-color: #add036;
}

.circle .red {
    background-color: #ec2426;
}

.circle .yellow {
    background-color: #ffc116;
}

enter image description here

Upvotes: 3

Views: 2358

Answers (1)

cjol
cjol

Reputation: 1495

Simply create new divs programatically (for example using $("<div />")) and assign the width, height and position properties randomly. For example, to create one circle, I might do something like this:

var newCircle = $("<div />")
var d = Math.floor(Math.random() * maxDiam);
newCircle.addClass("circle");

newCircle.css({
    width: d,
    height: d,
    left: Math.random() * Math.max($("#container").width() - d, 0),
    top: Math.random() * Math.max($("#container").height - d, 0),
    backgroundColor: getRandomColor()
});
$("#container").append(newCircle);

You could either choose truly random colours (for example using this solution: Random circles with jQuery), or just choose from the colours you selected:

function getRandomColor() {
    var colours = ["#00c0f1", "#add036", "#ec2426", "#ffc116"];
    return colours[Math.floor(Math.random() * 4)]
}

Here is a full example putting that all together: http://jsfiddle.net/hephistocles/b63ja0h3/3/

Upvotes: 6

Related Questions