如何访问与Chart.js中当前工具提示回调有关的图表实例



我试图在甜甜圈图中显示百分比值。为了正确工作,我需要在回调中访问图表实例。我不知道该怎么做?

我处理了使用 Chart.pluginservice beforeDraw事件,但它无法正常工作。

有什么方法可以从工具提示回调中的beforedraw事件移动代码?

这是我的代码

tooltips: {
    callbacks: {
    label: function (tooltipItem, data) {
        var precentage = dataFromDoughnutChart;
        localStorage.setItem("per", precentage.toString());
        return precentage + "%";
    }
}
}
Chart.pluginService.register({
        beforeDraw: function (chart) {
            var value = "";
            var x = localStorage.getItem("per");
            if (x != null)
                value = x + "%";
            var width = chart.chart.width,
                height = chart.chart.height,
                ctx = chart.chart.ctx;
            ctx.restore();
            var fontSize = (height / 100).toFixed(2);
            ctx.font = fontSize + "em sans-serif";
            ctx.textBaseline = "middle";
            var text = value,
                textX = Math.round((width - ctx.measureText(text).width) / 2),
                textY = height / 2;
            ctx.fillText(text, textX, textY);
            ctx.save();
        },
        afterEvent: function (chart, event) {
            if (event.type == "mouseout") {
                localStorage.removeItem("per");
            }
        }
    });

我认为解决问题的最佳方法是实际使用自定义工具提示而不是尝试插件。这是我从图表之一中修改的一个工作解决方案。

首先为Yout HTML中的自定义工具提示定义一个容器。

<div id="chartjs-tooltip"></div>

然后使用以下自定义工具提示函数。您可能必须根据需要调整centerX计算。此函数基本上可以计算当前有效切片的百分比值(通过将数据点除以数据点的总值),将其放置在自定义工具提示div中,并将DIV放置在甜甜圈的中心。

Chart.defaults.global.tooltips.custom = function(tooltip) {
  // Tooltip Element
  var tooltipEl = document.getElementById('chartjs-tooltip');
  // Hide if no tooltip
  if (tooltip.opacity === 0) {
    tooltipEl.style.opacity = 0;
    return;
  }
  // Set Text
  if (tooltip.body) {
    var total = 0;
    // get the value of the datapoint
    var value = this._data.datasets[tooltip.dataPoints[0].datasetIndex].data[tooltip.dataPoints[0].index].toLocaleString();
    // calculate value of all datapoints
    this._data.datasets[tooltip.dataPoints[0].datasetIndex].data.forEach(function(e) {
      total += e;
    });
    // calculate percentage and set tooltip value
    tooltipEl.innerHTML = '<h1>' + (value / total * 100) + '%</h1>';
  }
  // calculate position of tooltip
  var centerX = (this._chartInstance.chartArea.left + this._chartInstance.chartArea.right) / 2;
  var centerY = ((this._chartInstance.chartArea.top + this._chartInstance.chartArea.bottom) / 2);
  // Display, position, and set styles for font
  tooltipEl.style.opacity = 1;
  tooltipEl.style.left = centerX + 'px';
  tooltipEl.style.top = centerY + 'px';
  tooltipEl.style.fontFamily = tooltip._fontFamily;
  tooltipEl.style.fontSize = tooltip.fontSize;
  tooltipEl.style.fontStyle = tooltip._fontStyle;
  tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
};

这是通过Codepen的完整端到端工作示例:

Chart.js甜甜圈中心百分比

最新更新