Events

This sample demonstrates how to use the event hooks to highlight chart elements.

Events - 图1

config handleHover handleLeave data

  1. const config = {
  2. type: 'pie',
  3. data: data,
  4. options: {
  5. plugins: {
  6. legend: {
  7. onHover: handleHover,
  8. onLeave: handleLeave
  9. }
  10. }
  11. }
  12. };
  1. // Append '4d' to the colors (alpha channel), except for the hovered index
  2. function handleHover(evt, item, legend) {
  3. legend.chart.data.datasets[0].backgroundColor.forEach((color, index, colors) => {
  4. colors[index] = index === item.index || color.length === 9 ? color : color + '4D';
  5. });
  6. legend.chart.update();
  7. }
  1. // Removes the alpha channel from background colors
  2. function handleLeave(evt, item, legend) {
  3. legend.chart.data.datasets[0].backgroundColor.forEach((color, index, colors) => {
  4. colors[index] = color.length === 9 ? color.slice(0, -2) : color;
  5. });
  6. legend.chart.update();
  7. }
  1. const data = {
  2. labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
  3. datasets: [{
  4. label: '# of Votes',
  5. data: [12, 19, 3, 5, 2, 3],
  6. borderWidth: 1,
  7. backgroundColor: ['#CB4335', '#1F618D', '#F1C40F', '#27AE60', '#884EA0', '#D35400'],
  8. }]
  9. };

Docs