Reputation: 353
I got a script that generates 100 elements and appends them to the site. I'm using jquery to let the elements move to the left or right side but I was wondering if there would be some kind of algorithm to create a cross or a cirle out of those elements.
So you have 100 small boxes and the algorithm moves them around and formes a circle or other easy symbols.
I did some researching but I couldn't find something usable.
Upvotes: 2
Views: 151
Reputation: 21368
Note: This is a super hacky, quickly put together solution that has a couple obvious flaws, but I'm sure that you can work those out for yourself:
Here's what I might do (well, a little cleaner, but it would probably be along these lines):
$(function(){
// generate the boxes
for(var n = 0; n < 100; ++n) {
$("<div/>",
{
id: n,
style: "width: 20px;\
height: 20px;\
background-color: red;\
position: absolute;",
}
).appendTo("#container");
}
var mid = {
x: 250,
y: 250
};
var w = 300;
function circle() {
for(var n = 0; n < 100; ++n) {
$("#"+n).css("top", (mid.y + (Math.sin(Math.PI/((n+1)/100)) * w/2)));
$("#"+n).css("left", (mid.x + (Math.cos(Math.PI/((n+1)/100)) * w/2)));
}
}
function square() {
// top
var n = 0;
for(; n < 25; ++n) {
$("#"+n).css("top", mid.y - 150);
$("#"+n).css("left", w * (n/25) + mid.x / 2);
}
// right
for(; n < 50; ++n) {
$("#"+n).css("top", (w * ((n-25)/25)) + mid.y/2);
$("#"+n).css("left", mid.x + w/2);
}
// bottom
for(; n < 75; ++n) {
$("#"+n).css("top", mid.y + 300/2);
$("#"+n).css("left", w * ((n-50)/25) + mid.x / 2);
}
// left
for(; n < 100; ++n) {
$("#"+n).css("top", (w * ((n-75)/25)) + mid.y/2);
$("#"+n).css("left", mid.x - w/2);
}
}
var fns = [circle,
square];
var idx = 0;
setInterval(function() {
fns[idx]();
if(++idx >= fns.length) idx = 0;
}.bind(this), 1000);
});
Upvotes: 3