我有一个带自定义工具提示回调的2个数据集的甜甜圈图。我试图隐藏其中一个数据集的工具提示。我有它所有的工作,但我得到一堆js错误,当我悬停第二个数据集。这是我的。代码:
const data = {
labels: ' . $custom_label . ',
datasets: [
{
data: ' . $vdata . ',
backgroundColor: [ "#f56954", "#00a65a", "#f39c12", "#00c0ef", "#3c8dbc" ],
hoverOffset: 4
},
{
data: ' . $cdata . ',
backgroundColor: [ "#fff", "#fff", "#fff", "#fff", "#fff" ],
hoverBackgroundColor: [ "#fff", "#fff", "#fff", "#fff", "#fff" ],
hoverBorderColor: [ "#fff", "#fff", "#fff", "#fff", "#fff" ],
}
]
};
const config = {
type: "doughnut",
data: data,
options: {
cutoutPercentage: 40,
legend: {
display: false
},
tooltips: {
filter: function (tooltipItem) {
return tooltipItem.datasetIndex === 0;
},
callbacks: {
title: function(tooltipItem, data) {
var dataset = data["datasets"][0];
var percent = Math.round((dataset["data"][tooltipItem[0]["index"]] / dataset["_meta"][0]["total"]) * 100)
return data["labels"][tooltipItem[0]["index"]] + " " + percent + "%";
},
label: function(tooltipItem, data) {
var dataset = data["datasets"][0];
var value = dataset["data"][tooltipItem["index"]];
return "$" + (Math.round(value * 100) / 100).toFixed(2);
},
afterLabel: function(tooltipItem, data) {
var dataset = data["datasets"][1];
return dataset["data"][tooltipItem["index"]] + " " + data["labels"][tooltipItem["index"]];
}
},
titleFontColor: "#fff",
titleFontSize: 14,
backgroundColor: "#000",
bodyFontColor: "#fff",
bodyFontSize: 14,
bodySpacing: 4,
displayColors: false
}
}
};
var assetsChart = new Chart( document.getElementById("assetsChart"), config );
我假设它在试图读取["index"]部分时出错,因为它不存在于第二个数据集。
编辑:我更新以显示我的图表的完整代码
如何解决这个问题?
您使用的是非常旧的Chart.js
版本。您应该首先切换到最新版本(当前为v3.5.1
)。
请看看下面修改和可运行的代码,看看它如何使用Chart.js
v3.5.1
工作。
new Chart('chart', {
type: 'doughnut',
data: {
labels: ['One', 'Two', 'Three', 'Four', 'Five'],
datasets: [{
data: [5, 3, 7, 6, 7],
backgroundColor: ["#f56954", "#00a65a", "#f39c12", "#00c0ef", "#3c8dbc"],
hoverOffset: 4,
},
{
data: [2, 4, 5, 4, 6],
hidden: true
}
]
},
options: {
plugins: {
tooltip: {
filter: ctx => ctx.datasetIndex == 0,
callbacks: {
title: ctx => {
if (ctx.length) {
var data = ctx[0].dataset.data;
var value = data[ctx[0].dataIndex];
var total = data.reduce((a, b) => a + b, 0);
var percent = Math.round(value / total * 100);
return value + " " + percent + "%";
}
},
label: ctx => {
var value = ctx.dataset.data[ctx.dataIndex];
return "$" + (Math.round(value * 100) / 100).toFixed(2);
},
afterLabel: ctx => {
var hiddenDataset = ctx.chart.config._config.data.datasets[1].data;
var value = hiddenDataset[ctx.dataIndex];
return value + " " + ctx.label;
}
},
titleColor: "#fff",
titleFontSize: 14,
backgroundColor: "#000",
bodyFontColor: "#fff",
bodyFontSize: 14,
bodySpacing: 4,
displayColors: false
}
}
}
});
canvas {
max-height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="chart"></canvas>