我正在使用 Chart.js ( documentation ),但我似乎无法为 Donut 路径 设置背景色。它甚至没有在文档中提及。
我要实现的目标:
当前代码:
var meterInvoicesData = [
{
value: 75,
color: '#22d319'
},
{
value: 25, // rest
color: 'transparent' // invisible (setting this as background color will animate it too)
}
];
var meterOptions =
{
percentageInnerCutout : 80,
animationEasing : 'easeInQuint'
};
var meterInvoices = new Chart(document.getElementById('meterInvoices').getContext('2d')).Doughnut(meterInvoicesData,meterOptions);
更新:我目前通过使用值为 100、没有动画和我想要的(背景)颜色的复制 donut (第二个 Canvas )解决了这个问题,并且将其绝对定位在第一个下方。
然而,这是一个令人讨厌的技巧,而且效率很低,所以我仍然希望得到一个正确的答案。
最佳答案
我想我会发布一个对我有用的最新解决方案,使用引入了 plugins 的 v2.1.0 .
没有值显示背景的图表 vs 有值覆盖背景的图表,只有主图表会动画,背景只是一个简单的弧线:
我首先根据 their docs 注册了一个插件:
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"]
}]
}
});
关于javascript - Chart.js 设置 donut 背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19834763/