首先设计环图
1,准备数据
d = {
datasets: [
{
data: [10,34,65,23,76],
backgroundColor: ["#112845", "#2C5FA0", "#3E90F5", "#7EB7FA", "#AFD1F7", "#B9C1CB", "#8B939D", "#626A6F", "#464B4D", "#343434"],
//backgroundColor: colorArr
}
],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: ['TYPEA','TYPEB','TYPEC','TYPED','TYPEE']
};
2,画图
<canvas id="Canvas2" height="200vh"></canvas>
// 环图
var myPieChart = new Chart(ctx1, {
type: "pie",
data: d,
options: {
cutoutPercentage: 60,
title: {
display: false
},
legend: {
display: true,
position: "top",
align: "start",
fullWidth: true,
labels: {
boxWidth: 15,
fontColor: "rgb(0, 0, 255)",
padding: 5
}
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0
}
},
plugins: {
datalabels: {
color: 'white',
labels: {
title: {
font: {
weight: 'bold'
}
},
value: {
color: 'green'
}
}
}
},
annotation: {
annotations: [
{
type: 'line',
mode: 'horizontal',
scaleID: 'y-axis-0',
value: 25,
draggable: true,
onDrag: function (event) {
console.log(event.subject.config.value);
}
}
]
},
elements: {
center: {
text: totalArr1,
color: '#32629F',
fontStyle: 'HGPGothicE',
sidePadding: 20
}
}
},
});
3,配置
```Chart.pluginService.register({
beforeDraw: function (chart) {
if (chart.config.options.elements.center) {
//Get ctx from string
var ctx = chart.chart.ctx;
//Get options from the center object in options
var centerConfig = chart.config.options.elements.center;
var fontStyle = centerConfig.fontStyle || 'Arial';
var txt = "TOTAL " + centerConfig.text;
var txt2 = 'TOTAL';
var txt3 = centerConfig.text;
var color = centerConfig.color || '#000';
var sidePadding = centerConfig.sidePadding || 20;
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
//Start with a base font of 30px
ctx.font = "30px " + fontStyle;
//Get the width of the string and also the width of the element minus 10 to give it 5px side padding
var stringWidth = ctx.measureText(txt).width;
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;
// Find out how much the font can grow in width.
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var elementHeight = (chart.innerRadius * 2);
// Pick a new font size so it will not be larger than the height of label.
var fontSizeToUse = Math.min(newFontSize, elementHeight);
//Set font settings to draw it correctly.
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
ctx.font = fontSizeToUse + "px " + fontStyle;
//Draw text in center
// 主要是下边这两行代码,一行是写总计上边,一行写总计下边,最后分行显示
// 上边显示黑色,下边显示深蓝色
ctx.fillStyle = 'black';
ctx.fillText(txt2, centerX, centerY-25);
ctx.fillStyle = color;
ctx.fillText('_________', centerX, centerY-10 );
ctx.fillText(toThousands(txt3), centerX, centerY + 25);
}
}
});