效果
这是实现后的效果:
版本
在实现这个现实的过程中,Chart.Js的版本也比较重要,这里使用的版本是2.1.0,请务必确认版本,在更高的版本可能会有更好的方案。
过程
需要在创建的chart前加入:
Chart.pluginService.register({
beforeRender: function (chart) {
if (chart.config.options.showAllTooltips) {
// create an array of tooltips
// we can't use the chart tooltip because there is only one tooltip per chart
chart.pluginTooltips = [];
chart.config.data.datasets.forEach(function (dataset, i) {
chart.getDatasetMeta(i).data.forEach(function (sector, j) {
chart.pluginTooltips.push(new Chart.Tooltip({
_chart: chart.chart,
_chartInstance: chart,
_data: chart.data,
_options: chart.options,
_active: [sector]
}, chart));
});
});
// turn off normal tooltips
chart.options.tooltips.enabled = false;
}
},
afterDraw: function (chart, easing) {
if (chart.config.options.showAllTooltips) {
// we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
if (!chart.allTooltipsOnce) {
if (easing !== 1)
return;
chart.allTooltipsOnce = true;
}
// turn on tooltips
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
tooltip.initialize();
tooltip.update();
// we don't actually need this since we are not animating tooltips
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
})
创建表格的记录:
this.myChart = new Chart(ctx, {
type: 'bar',
data: patientAgeData,
options: {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var i = tooltipItem.index;
console.info(data.datasets)
var label = data.datasets[0].data[i];
return label+"名";
}
}
},
showAllTooltips: true
}
});
即可完成此任务!查了很多资料,最后才查到此方案,由于对JS了解不深。