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>
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?
Share Improve this question edited Oct 28, 2014 at 7:12 Scimonster 33.4k10 gold badges79 silver badges91 bronze badges asked Oct 28, 2014 at 7:10 Om3gaOm3ga 33.1k45 gold badges149 silver badges230 bronze badges 1-
4
Simply divide the width/height of the box by 2. For instance:
var radius = document.querySelector('.circle').offsetWidth / 2
– Hashem Qolami Commented Oct 28, 2014 at 7:13
3 Answers
Reset to default 3Since 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.
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>
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>