Chase
Chase

Reputation: 151

Arranging different height divs around a circle with a radius

So, I have been trying to create a large number of divs (we can call them bars) and have them rotated and positioned so that it creates a circle in the center. I am bad at explaining so here is an example where all bars have the same width and height.
JSFiddle Here:

Everything looks good here. However, the problem arises when I change the height of the bars. JSFiddle Here:

I assume my troubles arise from my positioning and rotating functions are messed up or the nature of the absolute positioning. Here is an example of my js for the second JSFiddle.

var $bars = [];
var viz = document.getElementById('viz');

function create(num) {
    for(var i = 0; i < num; i++) {
        var a = document.createElement('div');
        a.classList.add('bar');
        viz.appendChild(a);
        $bars.push($(a));
    }
}

create(256);

$(document).ready(function(){
    var step = Math.PI * 2 / $bars.length;
    var radius = 200;
    var angle = 0;

    for (var i = 0; i < $bars.length; i++) {
        var x = Math.round(radius * Math.cos(angle));
        var y = Math.round(radius * Math.sin(angle));
        $bars[i].css('left', x + 'px');
        $bars[i].css('top', y + 'px');
        $bars[i].css('height', i + 1);
        var rot = 90 + (1.4025 * i);
        $bars[i].css('transform', 'rotate(' + rot + 'deg)'); 
        angle += step;
    }
});

Is there a way to maintain the circle radius with all divs/bars even if the heights are different from my example? (I am relatively new a js so please forgive my poor code)

Upvotes: 1

Views: 54

Answers (2)

vals
vals

Reputation: 64164

I have added

transform-origin: center top;

to your styles. This way, the element grows only in one direction:

fiddle

Upvotes: 1

Neil
Neil

Reputation: 14313

The code is performing as intended, you are changing the height as you go around the circle. However, if you update the height to solid number then it will perform properly:

$bars[i].css('height', 20);

https://jsfiddle.net/rzt5L0sh/1/

Upvotes: 0

Related Questions