一个数据集上的自定义工具提示回调(chartjs v 2.5)

Custom tooltip callback on one dataset (chartjs v 2.5)

我有一个包含 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 版本太旧了。您应该先切换到 latest version(目前是 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>