以为我会发布一个最近对我有用的解决方案,使用 v2.1.0 引入了plugins。
没有值显示背景的图表与有值覆盖背景的图表,只有主图表会动画,背景只是一个简单的弧线:
我首先根据他们的文档注册了一个插件:
var radiusBackground = function() {
var self = this;
self.draw = function(chartInstance) {
if(chartInstance.options.radiusBackground) {
var x = chartInstance.chart.canvas.clientWidth / 2,
y = chartInstance.chart.canvas.clientHeight / 2,
ctx = chartInstance.chart.ctx;
ctx.beginPath();
ctx.arc(x, y, chartInstance.outerRadius - (chartInstance.radiusLength / 2), 0, 2 * Math.PI);
ctx.lineWidth = chartInstance.radiusLength;
ctx.strokeStyle = chartInstance.options.radiusBackground.color || '#d1d1d1';
ctx.stroke();
}
};
// see http://www.chartjs.org/docs/#advanced-usage-creating-plugins for plugin interface
return {
beforeDatasetsDraw: self.draw,
onResize: self.draw
}
};
// Register with Chart JS
Chart.plugins.register(new radiusBackground());
单例语法只是为了能够减少重复并draw
为多个插件事件使用相同的方法。
然后我像这样使用我的新注册插件:
var chartElement = document.getElementById('doughnut-chart');
var chart = new Chart(chartElement, {
type: 'doughnut',
options: {
// Here is where we enable the 'radiusBackground'
radiusBackground: {
color: '#d1d1d1' // Set your color per instance if you like
},
cutoutPercentage: 90,
title: {
display: false,
},
legend: {
display: false,
},
},
data: {
labels: ["Type 1", "Type 2", "Type 3"],
datasets: [{
data: [2, 5, 1],
backgroundColor: ["#a3c7c9","#889d9e","#647678"],
borderWidth: 0,
hoverBackgroundColor: ["#96b7b9","#718283","#5c6b6d"]
}]
}
});
JS小提琴在这里