首页 > 解决方案 > 使用图表颜色动态更改工具提示的背景颜色

问题描述

我有一个包含 4 个数据集的折线图,我想为所有 4 条线显示不同的工具提示背景。但是工具提示不支持动态背景颜色,无论如何该怎么做?

在此处输入图像描述

标签: chart.js

解决方案


工作“动态”示例。

***请记住对与您的数据结构相关的数据的访问。

使用tooltip-model https://www.chartjs.org/docs/2.7.3/configuration/tooltip.html#tooltip-model

“hello world”示例 - 将所有工具提示背景更改为red

tooltips: {
   custom: function(tooltipModel) {
   tooltipModel.backgroundColor = "red";
  }
},

代码片段:

var data = {
  labels: ["Africa", "Asia", "Europe", "America"],
  datasets: [{
    /* data */
    label: "Population (millions)",
    backgroundColor: ["red", "blue","green", 'purple'],
    data: [1000,1500,2000, 2200]
  }]
};

var options = {
  title: {
    text: 'Dynamically change tooltip background example',
    display: true
  },
  tooltips: {
    titleFontSize: 20,
    borderWidth: 2,
    borderColor: "white",
    displayColors: false, /* if true, color boxes are shown in the tooltip */
    /*########### Custom model ###########*/
    custom: function(tooltipModel) {
      /* if data & datasets not empty & tooltip available */
      if (tooltipModel.opacity !== 0 && data.labels.length && data.datasets.length) {
        /* get dataPoints index */
        var index = tooltipModel.dataPoints[0].index;
        /* get dataPoints datasetIndex */
        var dataSetIndex = tooltipModel.dataPoints[0].datasetIndex;
        /* get the current color on index and datasetIndex position */
        var color =  data.datasets[dataSetIndex].backgroundColor[index];
        /* set backgroundColor */
        tooltipModel.backgroundColor = color;
      };

    }
  },
  scales: {
    xAxes: [{
      stacked: true
    }],
    yAxes: [{
      stacked: true
    }]
  }
};

var myChart = new Chart(document.getElementById("chart"), {
  type: 'bar',
  data: data,
  options: options
});
<canvas id="chart" width="800" height="450"></canvas>



<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>

代码概要

  1. “如果”(为了避免控制台错误):
/*########### Custom model ###########*/
custom: function(tooltipModel) {
      /* if data & datasets not empty & tooltip available */
      if (tooltipModel.opacity !== 0 && data.labels.length && data.datasets.length) {
     /* do something */
     console.log(tooltipModel.dataPoints[0]); /* return object */

console.log返回对象:

Object {
  datasetIndex: 0,
  index: 1,
  label: "Asia",
  value: "1500",
  x: 338.6845703125,
  xLabel: "Asia",
  y: 215.28,
  yLabel: 1500
}
  1. 比我们dot (.) notation用来访问对象值的方式。
console.log(tooltipModel.dataPoints[0].index); /* return 1 */
  1. 我们使用这个索引“anchor”来获取backgroundColor数组的正确索引:
console.log(data.datasets[dataSetIndex].backgroundColor[index]); /* return "blue"
  1. 最后一步是使用这个颜色值:
/* set backgroundColor */
tooltipModel.backgroundColor = color;

用户界面

有用的隐藏 color boxes

displayColors: false, /* if true, color boxes are shown in the tooltip */

https://www.chartjs.org/docs/2.7.3/configuration/tooltip.html#tooltip-configuration

代码笔:

https://codepen.io/ezra_siton/pen/dyoQeGe?editors=1011


推荐阅读