2015-07-11 21 views
2

我用下面的代碼在圓中畫一條線,現在我想用相同的空間在不同角度畫12條線&線應該被觸摸到圓。如何使用for循環在不同角度的圓中畫一條線

<!DOCTYPE html> 
    <html> 
    <head> 

    <style> 

    #straight{ 
    height: 30px; 
    border-right: 1px solid blue; 
    -webkit-transform: rotate(**" for loop value must be displayed"** deg); 
    transform: rotate(**" for loop value must be displayed"** deg); 
    position: absolute; 
    top:40px; 
    left:400px; 
    } 
    #circle { 
     height: 30px; 
     width: 31px; 
     margin-left: 81px; 
     margin-top: 0px; 
     background-color: #fff; 
     border: 2px solid blue; 
     border-radius: 65px; 
     position:absolute; 

    }  
    </style>  
    </head>  
    <body> 

         <div> 
           <div id="circle">      
           <div style="position:relative; top:-40px; left:-385px;"> 
            <div id="straight"></div> 

          </div> 
         </div> 

    </body> 
    </html> 

請幫我提前&感謝

+0

你可以爲你想要實現的目標添加一個圖像,並顯示你目前能夠做什麼,或者你的代碼有什麼問題? – hoijui

+0

如果您運行此代碼,您可以看到,我正在嘗試製作輪子。提前感謝。 –

回答

0

檢查這個fiddle

它使用函數DrawLine(x1,y1,x2,y2)在給定的座標之間畫一條線。

基本上,它會創建寬度較薄的div,並根據斜率旋轉它們。

看起來像一個輪輻輪。

如果需要,這裏是一個。

以下是摘錄。

drawNLines(12, 40, 40, 40); 
 

 
function drawNLines(N, centreX, centreY, radius) { 
 
    for (i = 0; i < N; i++) { 
 
    angle = 360/N; 
 
    x2 = centreX + radius * Math.cos(Math.PI * angle * i/180); 
 
    y2 = centreY + radius * Math.sin(Math.PI * angle * i/180); 
 
    DrawLine(centreX, centreY, x2, y2); 
 
    } 
 
} 
 

 

 
function DrawLine(x1, y1, x2, y2) { 
 

 
    if (y1 < y2) { 
 
    var pom = y1; 
 
    y1 = y2; 
 
    y2 = pom; 
 
    pom = x1; 
 
    x1 = x2; 
 
    x2 = pom; 
 
    } 
 

 
    var a = Math.abs(x1 - x2); 
 
    var b = Math.abs(y1 - y2); 
 
    var c; 
 
    var sx = (x1 + x2)/2; 
 
    var sy = (y1 + y2)/2; 
 
    var width = Math.sqrt(a * a + b * b); 
 
    var x = sx - width/2; 
 
    var y = sy; 
 

 
    a = width/2; 
 

 
    c = Math.abs(sx - x); 
 

 
    b = Math.sqrt(Math.abs(x1 - x) * Math.abs(x1 - x) + Math.abs(y1 - y) * Math.abs(y1 - y)); 
 

 
    var cosb = (b * b - a * a - c * c)/(2 * a * c); 
 
    var rad = Math.acos(cosb); 
 
    var deg = (rad * 180)/Math.PI 
 

 
    htmlns = "http://www.w3.org/1999/xhtml"; 
 
    div = document.createElementNS(htmlns, "div"); 
 
    div.setAttribute('style', 'border:1px solid black;width:' + width + 'px;height:0px;-moz-transform:rotate(' + deg + 'deg);-webkit-transform:rotate(' + deg + 'deg);position:absolute;top:' + y + 'px;left:' + x + 'px;'); 
 

 
    document.getElementById("circle").appendChild(div); 
 

 
}
#circle { 
 
    height: 80px; 
 
    width: 80px; 
 
    margin-left: 30px; 
 
    margin-top: 30px; 
 
    background-color: #fff; 
 
    border: 2px solid blue; 
 
    border-radius: 80px; 
 
    position: absolute; 
 
}
<div id="circle"></div>

希望這有助於。 :)

+0

謝謝Shrinivas ..... –

+0

這是一個很好的做法,以「接受」和「Upvote」(如果允許)有用的答案,因爲它可以幫助未來訪問此問題的每個人。 –