Raphael.js - convert a pie chart to a donut chart

I am trying to use the raphael.js example located here:

http://raphaeljs.com/pie.html

but I want to convert a pie chart to a donut chart (have a hole in the middle of all slices). Currently, each slice is created with the following code:

function sector(cx, cy, r, startAngle, endAngle, params) { //console.log(params.fill); var x1 = cx + r * Math.cos(-startAngle * rad), x2 = cx + r * Math.cos(-endAngle * rad), y1 = cy + r * Math.sin(-startAngle * rad), y2 = cy + r * Math.sin(-endAngle * rad); return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params); } 

How do I change this so that the fixed-radius hole is removed from the common pie? I saw this post here that helps, but I can’t say how and where to apply it to my code above:

How to reach the "donut holes" with paths in Raphael

+4
source share
2 answers

The way to create one piece of cake is as follows:

  • move to the center of the circle (cx, cy): "M", cx, cy
  • draw a line to the edge where the arc (x1, y1) starts: "L", x1, y1
  • draw an arc based on some mathematical calculations: "A", r, r, 0, + (endAngle - startAngle> 180), 0, x2, y2
  • draw a line to the middle of the circle: in this case "z" is used; this means moving to the origin (cx, cy)

and the cut (path) is ready.

To create a donut, you need to change the way you create the path. You need to have a path consisting of two arcs (inside and outside) and 2 lines to complete it.

So, first you need to find the starting point for the path based on the radius of the imaginary empty circle that will be in the middle of the donut (with radius rin ). Lets name the coordinates of this point xx1 and yy1:

 xx1 = cx + rin * Math.cos(-startAngle * rad) yy1 = cy + rin * Math.sin(-startAngle * rad) 

You begin to build a path from this point ( "M", xx1, yy1 ); http://jsfiddle.net/EuMQ5/425/

The next step is to draw a line to the edge of the circle ( "L", x1, y1 ). From there you will have to draw an external arc ( "A", r, r, 0, + (endAngle - startAngle> 180), 0, x2, y2 ), then another line to the other edge of the internal arc ( "L", xx2, yy2 ) To get the values ​​for xx2 and yy2:

 xx2 = cx + rin * Math.cos(-endAngle * rad) yy2 = cy + rin * Math.sin(-endAngle * rad) 

and the last step is to complete the path by plotting the inner arc ( "A", rin, rin, 0, + (endAngle - startAngle> 180), 1, xx1, yy1 ), and now you have a piece of donut.

The violin is here.

** updated fiddle link

+20
source

Why don't you just draw a circle in the center of the pie chart?

 paper.add([ { type: "circle", cx: 250, cy: 250, r: 150, fill: "#ffffff" }, ]); 
0
source

Source: https://habr.com/ru/post/1379207/


All Articles