Chart.js:鼠标悬停时,线系列(在许多之中)如何改变线的颜色和粗细?

时间:2019-02-08 18:18:27

标签: javascript chart.js chartjs-2.6.0

我创建了具有多条线(默认情况下为1像素厚度)的Chart.js线图,并且希望用户能够将鼠标悬停在任何特定的线图上(而不仅仅是点),并更改图它的线宽(即3像素)。在Chart.js中可以做到吗?

1 个答案:

答案 0 :(得分:1)

想法是找到与要更改的绘图线相对应的数据集对象,更新其borderWidth属性,然后调用chart.update()

下面是一个示例,请注意onHover函数。

var config = {
  type: 'line',
  options: {
    tooltips: {
      mode: 'nearest',
      intersect: false,
    },
    hover: {
      mode: 'nearest',
      intersect: false
    },


    // LOOK AT ME!!! I'M SO IMPORTANT!!!
    onHover: function onHover (evt, activeElements) {
      if (!activeElements || !activeElements.length) return;
      var datasetIndex = activeElements[0]._datasetIndex;
      var activeDataset = this.data.datasets[datasetIndex];
      activeDataset.borderWidth = 5;
      this.update();
    },


  },
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'BlueLine',
      fill: false,
      backgroundColor: window.chartColors.blue,
      borderColor: window.chartColors.blue,
      data: [57, 66, 17, 23, 16, 38, 60, 25, 5],
    }, {
      label: 'RedLine',
      fill: false,
      backgroundColor: window.chartColors.red,
      borderColor: window.chartColors.red,
      data: [23, 6, 32, 57, 38, 17, 19, 7, 23],
    }]
  },
};

var ctx = document.getElementById('canvas').getContext('2d');
window.myLine = new Chart(ctx, config);