How to divide a circle into n parts

When I was looking for this solution one answer that I had found everywhere –

fill the circle with a different color by using CSS rotation and transform property, but what if you don’t want your circle colorful.

I am going to implement circle division using javascript.

Technologies

Technologies that I am going to use are bootstrap 4 and javascript.

Approach

I am going to have a div as a circle.

circle-div d-flex align-items-center justify-content-centerthese are bootstrap4 CSS that align content inside div with id “outerCirlceId” vertically and horizontally centered.

To convert it into circle use following CSS –

this will create a circle with background grey.

Now I am going to have a div inside above div(outer) div. And this inside div don’t have height and width.

Now we have a outer circle and an inner circle without any height and width.

If we want to divide this circle into n parts. So I am going to have n points on a circle on equidistance and draw a line from these points to the inner circle.

getCenter

In this method first, calculate offset of center div. I have stored this value object centerObj and also provide height and width of 1 px to this object. Now we have all the information of center div stored in object centerObj.

In above example I want to divide a circle into 12 parts. And diameter of circle is 400 equal to height and width. So have taken r equal to 200 that is radius.

 

items number of part in which you want to divide the circle.

x0, y0 center points

x1, y1 first points on circle

x2, y2 second points on circle

first point calculation

var x = x0 + r * Math.cos(2 * Math.PI * 0 / 12);  

ie   center div x coordinate + radius * cos (360*0/12)

var y = y0 + r * Math.sin(2 * Math.PI * 0 / 12);

center div y coordinate + radius * sin (360*0/12).

After the iteration of all 12 points, you have all the coordinate in cordinateArr.

 

Now you have points on circle and center div coordinate. Now you need to draw a line from each point on the circle to center div.

var length = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1))) use to get length between two points

var angle = Math.atan2((y1-y2),(x1-x2))*(180/Math.PI); this return angle between positive x axis and point ((y1-y2),(x1-x2)).

 

I don’t think other parts of above functionality need any explanation.

You will get below output for 12 division of the circle.

 

 

You can get the complete code from below github link – https://github.com/visheshmishra/circle_division

Please follow and like us:
20

Leave a Reply