Chartjs-Fade other lines when hovering legend in Chart.js

1👍

For Chart.JS 2.x:

Example: https://jsfiddle.net/rn7ube7v/4/

We need to switch between 2 dataset.borderColors where 1 color has an alpha of 0.2 (20% visible) and 1 (100% visible).

Eg: Using HSL colors to cycle the rainbow for each dataset, we store both the regular color as dataset.accentColor and dataset.accentFadedColor for when it’s not focused.

function steppedHslColor(ratio, alpha) {
  return "hsla(" + 360 * ratio + ', 60%, 55%, ' + alpha + ')';
}
function colorizeDatasets(datasets) {
  for (var i = 0; i < datasets.length; i++) {
    var dataset = datasets[i]

    dataset.accentColor = steppedHslColor(i / datasets.length, 1)
    dataset.accentFadedColor = steppedHslColor(i / datasets.length, 0.2)

    dataset.backgroundColor = dataset.accentColor
    dataset.borderColor = dataset.accentColor
  }
  return datasets
}

colorizeDatasets(datasets)

Then we hook options.legend.onHover(mouseEvent, legendItem) to apply the right color.

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: datasets,
  },
  options: {
    legend: {
      onHover: function(e, legendItem) {
        if (myChart.hoveringLegendIndex != legendItem.datasetIndex) {
          myChart.hoveringLegendIndex = legendItem.datasetIndex
          for (var i = 0; i < myChart.data.datasets.length; i++) {
            var dataset = myChart.data.datasets[i]
            if (i == legendItem.datasetIndex) {
              dataset.borderColor = dataset.accentColor
            } else {
              dataset.borderColor = dataset.accentFadedColor
            }
          }
          myChart.update()
        }
      }
    },
  },
});

There isn’t a config.legend.onLeave callback unfortunately, so we need to hook canvas.onmousemove and see if it leaves the legend area.

myChart.hoveringLegendIndex = -1
myChart.canvas.addEventListener('mousemove', function(e) {
  if (myChart.hoveringLegendIndex >= 0) {
    if (e.layerX < myChart.legend.left || myChart.legend.right < e.layerX
      || e.layerY < myChart.legend.top || myChart.legend.bottom < e.layerY
    ) {
      myChart.hoveringLegendIndex = -1
      for (var i = 0; i < myChart.data.datasets.length; i++) {
        var dataset = myChart.data.datasets[i]
        dataset.borderColor = dataset.accentColor
      }
      myChart.update()
    }
  }
})

Leave a comment