HTMLcopy
1
<div id="container"></div>
CSScopy
6
1
html, body, #container {
2
width: 100%;
3
height: 100%;
4
margin: 0;
5
padding: 0;
6
}
JavaScriptcopy
x
1
anychart.onDocumentReady(function () {
2
3
// create data
4
var data = [
5
{x: "A long label", value: 637166},
6
{x: "B one more label, but much longer than previous", value: 721630},
7
{x: "C", value: 148662},
8
{x: "D", value: 78662},
9
{x: "E", value: 90000}
10
];
11
12
// create a chart and set the data
13
var chart = anychart.pie(data);
14
15
// create an iterator variable
16
let longestLabelChars = 0
17
// set the position of labels
18
chart.labels().position("outside").format(function(e){
19
if(longestLabelChars < e.x.length){
20
longestLabelChars = e.x.length
21
}
22
return e.x
23
});
24
25
26
27
//show labels length before a chart was drawn
28
console.log(`Before draw - ${longestLabelChars}`)
29
30
chart.radius("100%");
31
32
33
// configure connectors
34
chart.connectorStroke({color: "#595959", thickness: 2, dash:"2 2"});
35
36
//create Resize observer
37
const resizeObserver = new ResizeObserver((entries) => {
38
const currentContainerWidth = entries[0].contentRect.width;
39
//set up your radius break point in pixels
40
//assuming that average char width is 7 px
41
const maxLabelLength = longestLabelChars*7;
42
43
//create a break point variable, which is 3 legths of labels + additional space
44
const breakPoint = (maxLabelLength*2) + 50;
45
46
//trim labels based on charts width
47
chart.labels().maxLength(currentContainerWidth/longestLabelChars)
48
49
// set labels position to "inside" when chart is too small
50
if (chart.getPixelRadius() < 10 && currentContainerWidth < breakPoint) {
51
console.log("switch labels position to INSIDE")
52
chart.labels().position("inside")
53
chart.title("Pie Chart: Inner Labels")
54
}
55
// set labels position to "outside" when chart is expanding
56
else if(currentContainerWidth > breakPoint){
57
console.log("switch labels position to OUTSIDE", maxLabelLength)
58
chart.labels().position("outside")
59
chart.title("Pie Chart: Outer Labels")
60
}
61
62
});
63
64
//observe a container resize
65
resizeObserver.observe(document.getElementById("container"));
66
67
68
// disable the legend
69
chart.legend(false);
70
71
// set the chart title
72
chart.title("change container size to change labels position");
73
74
// set the container id
75
chart.container("container");
76
77
// initiate drawing the chart
78
chart.draw();
79
chart.labels().maxLength(longestLabelChars);
80
81
console.log(`After draw - ${longestLabelChars}`)
82
});