2012-04-14 17 views
31

円の周りにいくつかの要素を配置する関数を探しています。
結果のようなものでなければなりません:円の周りにいくつかの要素を動的に配置する

enter image description here

+10

@camus私の本当の問題は三角法を知らないことです; – Omid

+0

4要素または同じ距離の 'n'要素だけ? – Neysor

+0

異なる距離の@Neysor「n」要素。 – Omid

答えて

62

ここであなたを助ける必要がありますいくつかのコードです:

var numElements = 4, 
    angle = 0 
    step = (2*Math.PI)/numElements; 
for(var i = 0; i < numElements.length; i++) { 
    var x = container_width/2 + radius * Math.cos(angle); 
    var y = container_height/2 + radius * Math.sin(angle); 
    angle += step; 
} 

それは完全ではありませんが、あなたに良いスタートを与える必要があります。


アップデート:ここでは実際に動作する何か:

var radius = 200; // radius of the circle 
var fields = $('.field'), 
    container = $('#container'), 
    width = container.width(), 
    height = container.height(), 
    angle = 0, 
    step = (2*Math.PI)/fields.length; 
fields.each(function() { 
    var x = Math.round(width/2 + radius * Math.cos(angle) - $(this).width()/2), 
     y = Math.round(height/2 + radius * Math.sin(angle) - $(this).height()/2); 
    $(this).css({ 
     left: x + 'px', 
     top: y + 'px' 
    }); 
    angle += step; 
}); 

デモ:http://jsfiddle.net/ThiefMaster/LPh33/
は、ここでは、要素数を変更することができimproved versionです。 (XY)における中心付近要素について

+0

サイクルはどこにあるのですか? – Omid

+0

円の座標を加え、要素の大きさの半分を 'x'と' y'から差し引く必要があります。 –

+1

実例を含めるように答えを更新しました。 – ThiefMaster

10

、距離R、要素の中心がに配置されるべきである:

N、要素の数である
(x + r cos(2kπ/n), y + r sin(2kπ/n)) 

kは、現在配置している要素の「番号」です(1〜nを含む)。

+1

私はあなたが ' x + r'、右? – Omid

+4

'xy'は数学の' x * y'と同じことを意味します。 –

+0

これは私を助けましたありがとう – Krishnan

-1

I'veは自動的に幅/ 2に等しい半径を有する円の周りdivを分配するThiefMasterのフィドルを改変

<div class="circle-distribute-container"> 
    <div class="circle-element">one</div> 
    <div class="circle-element">two</div> 
    <div class="circle-element">three</div> 
    <div class="circle-element">four</div> 
    <div class="circle-element">five</div> 
</div> 
<div class="circle-distribute-container"> 
    <div class="circle-element">another one</div> 
    <div class="circle-element">another two</div> 
    <div class="circle-element">another three</div> 
    <div class="circle-element">another four</div> 
</div> 

link

を参照してください:コンテナのdivの210
関連する問題