所以我和其中一位平面设计师一起完成了一项小任务,我们需要有一个类似于圆环图的图表,可以在morris.js
主页上看到tooltip
位于甜甜圈的中心,但我们正在使用chartjs
来获取精彩的加载动画。
经过一些调查,为了让Morris.js
尝试制作动画,发现这非常困难,所以我选择让ChartJs
看起来更像morris.js
。
为了增加复杂性(如此轻微),我们使用angular来实现很多逻辑,并实现了许多功能,所以我们选择angular-chartjs非常适合我们的目的。
现在到了细节。
到目前为止,我已经非常接近了,我认为要复制Morris JS所做的一般想法。我尝试在jsfiddle
中执行我的代码但由于某种原因我无法使angular-chart.js
起作用。
基本上我遇到的问题是在afterLabel函数中,我对如何将它放在中心感到有点困惑,因此主标签和afterLabel都以甜甜圈为中心。
我不会说我所做的代码特别令人愉快,但到目前为止似乎工作正常,所以任何建议都会非常感激。
我还应该注意,代码确实可以使用标准的chartjs,你可以找到这里的小提琴https://jsfiddle.net/maraket/5qpsztrm/,除了居中之外似乎工作正常。
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
maintainAspectRatio: false,
tooltips: {
bodyColor: "#000",
backgroundColor: "rgba(0,0,0,0)",
custom: function(tooltip) {
tooltip.bodyFontSize = this._chartInstance.innerRadius / 4;
var txt = [
(tooltip.beforeTitle || []).join('\n'), (tooltip.title || []).join('\n'), (tooltip.afterTitle || []).join('\n'), (tooltip.beforeBody || []).join('\n'), (tooltip.body || []).join('\n'), (tooltip.afterBody || []).join('\n'), (tooltip.beforeFooter || [])
.join('\n'), (tooltip.footer || []).join('\n'), (tooltip.afterFooter || []).join('\n')
];
txt = txt.join("\n");
tooltip.y = ((this._chartInstance.chartArea.bottom - this._chartInstance.chartArea.top) / 2) + this._chartInstance.chartArea.top - tooltip.bodyFontSize;
tooltip.x = (this._chart.width / 2) - (this._chart.ctx.measureText(txt).width / 1.5);
},
callbacks: {
label: function(tooltipItem, data) {
return data.labels[tooltipItem.index];
},
afterLabel: function(tooltipItem, data) {
return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
}
}
}
}
});