简体   繁体   中英

calculate radius of a circle using javascript

I am trying to calculate radius of a circle using javascript. I have following section with css

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

As the width and height of this circle is 100x100. How can I calculate its radius?

Since the radius is just half of the diameter, this is easy. The diameter is 100px, per width and height . Hence, radius is 100px / 2 = 50px.

If you just need to set a radius to make a perfect circle, use 50% radius. This way it doesn't depend on width/height and you don't need javascript:

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

While you could set the radius relatively by border-radius: 50% , you could simply divide the width / height of the box by 2 to get the radius.

For instance:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM