2014-10-28 83 views
1

我正在嘗試計算使用javascript的圓的半徑。我已用CSS使用javascript計算圓的半徑

.circle { 
 
    position: absolute; 
 
    width: 100px; 
 
    height: 100px; 
 
    border-radius: 70px; 
 
    background: red; 
 
}
<section class="circle"></section>

作爲寬度和高度該圓的以下部分是100×100。 如何計算其半徑?

+3

只需除以2的框的寬度/高度例如:( '圓')。'VAR半徑= document.querySelector offsetWidth/2' – 2014-10-28 07:13:40

回答

2

由於半徑只是直徑的一半,所以很容易。直徑爲100px,每widthheight。因此,半徑是100px/2 = 50px。

1

如果你只需要設置一個半徑來製作一個完美的圓,使用半徑爲50%。這樣,它不依賴於寬/高,你並不需要的JavaScript:

.circle { 
 
    position: absolute; 
 
    width: 100px; 
 
    height: 100px; 
 
    border-radius: 50%; 
 
    background: red; 
 
}
<section class="circle"></section>

1

雖然你可以通過border-radius: 50%相對設置半徑,你可以簡單地劃分width/height通過2得到半徑。

例如:

var circle = document.querySelector('.circle'), 
 
    radius = circle.offsetWidth/2; 
 

 
circle.innerHTML = "Radius: " + radius + "px";
.circle { 
 
    position: absolute; 
 
    width: 100px; 
 
    height: 100px; 
 
    
 
    border-radius: 50%; /* I don't know if you really need to get the value of this */ 
 
    background: red; 
 
    
 
    line-height: 100px; 
 
    text-align: center; 
 
}
<section class="circle"></section>