如何更改悬停 Chartjs 上的图例图标

问题描述

我正在尝试自定义 chartjs 图例,以便当您将鼠标悬停在图例项上时,图标/点样式会发生变化。请参阅屏幕截图 Screenshot。这可能吗?

我正在尝试使用 onHover 属性进行不同的操作,但没有成功。

 legend: {
            display: true,onHover: function (event,legendItem,legend) {
            //Change Point style to icon
            },onLeave: function (e) {
            //Change back to normal
            }
        },

解决方法

是的,这是可能的,您可以更新您悬停的给定数据集的 pointStyle,您可以传递 chart.js 的任何预定义 pointStyles 或文档中描述的图像 (https://www.chartjs.org/docs/master/configuration/elements.html#point-styles)>

示例:

var options = {
  type: 'bar',data: {
    labels: ["Red","Blue","Yellow","Green","Purple","Orange"],datasets: [{
      label: '# of Votes',data: [12,19,3,5,2,3],backgroundColor: 'red'
    }]
  },options: {
    plugins: {
      legend: {
        labels: {
          usePointStyle: true
        },onHover: (evt,item,legend) => {
          legend.chart.data.datasets[item.datasetIndex].pointStyle = 'rectRot'
          legend.chart.update();
        },onLeave: (evt,legend) => {
          legend.chart.data.datasets[item.datasetIndex].pointStyle = ''
          legend.chart.update();
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx,options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.2/chart.js"></script>
</body>