简体   繁体   中英

How to change legend icon on hover Chartjs

I am trying to customize a chartjs legend so that when you hover over a legend item, the icon/point style will change. See screenshot Screenshot . Is this possible?

I am trying different things with the onHover property but am not having success.

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

Yes this is possible, you can update the pointStyle of the given dataset you are hovering, you can pass any of the predefined pointStyles of chart.js or an image as decribed in the documentation ( https://www.chartjs.org/docs/master/configuration/elements.html#point-styles )

Example:

 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, item, 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM