将图例悬停在图表.js中时淡入淡出其他线条



当我将"苹果"悬停在图例中时,如何使其他线条半透明?

对于图表.JS 2.x:

示例:https://jsfiddle.net/rn7ube7v/4/

我们需要在 2dataset.borderColor秒之间切换,其中 1 种颜色的 alpha 为0.2(20% 可见(和1(100% 可见(。

例如:使用HSL颜色为每个数据集循环彩虹,我们将常规颜色存储为dataset.accentColor,并在未聚焦时存储dataset.accentFadedColor

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)

然后我们钩住options.legend.onHover(mouseEvent, legendItem)以应用正确的颜色。

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()
}
}
},
},
});

不幸的是,没有config.legend.onLeave回调,因此我们需要挂钩canvas.onmousemove,看看它是否离开图例区域。

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()
}
}
})

最新更新