Distributing elements on a circle with the right angles
by tnhu
HTML
<section class="stage"></section>
CSS
*{margin:0;padding:0;font-size:15px;font-family:helvetica,arial,sans-serif}
footer,section,header{display:block;}
h1{margin:1em 2em}
.stage{
width:400px;
height:400px;
margin:2em;
float:left;
position:relative;
background:#ccc;
overflow:hidden;
font-weight:bold;
text-align:center;
}
JavaScript
Plot = function ( stage ) {
this.setDimensions = function( x, y ) {
this.elm.style.width = x + 'px';
this.elm.style.height = y + 'px';
this.width = x;
this.height = y;
};
this.position = function( x, y ) {
var xoffset = arguments[2] ? 0 : this.width / 2;
var yoffset = arguments[2] ? 0 : this.height / 2;
this.elm.style.left = (x - xoffset) + 'px';
this.elm.style.top = (y - yoffset) + 'px';
this.x = x;
this.y = y;
};
this.setBackground = function( col ) {
this.elm.style.background = col;
};
this.kill = function() {
stage.removeChild( this.elm );
};
this.rotate = function( str ) {
this.elm.style.webkitTransform = this.elm.style.MozTransform =
this.elm.style.OTransform = this.elm.style.transform =
'rotate(' + str + ')';
};
this.content = function( content ) {
this.elm.innerHTML = content;
};
this.round = function( round ) {
this.elm.style.borderRadius = round ? '50%/50%' : '';
};
this.elm = document.createElement( 'div' );
this.elm.style.position = 'absolute';
stage.appendChild( this.elm );
};
var stage = document.querySelector('.stage'),
plots = 10,
increase = Math.PI * 2 / plots,
angle = 0,
x = 0,
y = 0;
for( var i = 0; i < plots; i++ ) {
var p = new Plot( stage );
p.setBackground( 'green' );
p.setDimensions( 40, 40 );
x = 100 * Math.cos( angle ) + 200;
y = 100 * Math.sin( angle ) + 200;
p.rotate( Math.atan2( y - 200, x - 200 ) + 'rad' );
p.position( x, y );
angle += increase;
}