Chartjs-How to set gradient in legend box color in Chart,js

0👍

Take a look at this: Chart.js Legend Item interface

You can achieve this like so:

let maxLeft = 0;
let maxWidth = 0;
function generateLabelsNew(chart) {
    const datasets = chart.data.datasets;
    const {labels: {usePointStyle, pointStyle, textAlign, color}} = chart.legend.options;
    
    return chart._getSortedDatasetMetas().map((meta) => {
        const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
        const borderWidth = style.borderWidth;
        
        const box = meta?.controller?.chart?.legend?.legendHitBoxes[meta.index];

        if (box?.left > maxLeft) {
            maxLeft = box.left;
        }
        if (box?.width > maxWidth) {
            maxWidth = box.width;
        }
        const gradient = chart.ctx.createLinearGradient(maxLeft, 0, maxLeft + maxWidth, 0);
        gradient.addColorStop(0, 'green');
        gradient.addColorStop(1, 'red');
        
        return {
            text: datasets[meta.index].label,
            fillStyle: gradient,//style.backgroundColor,
            fontColor: color,
            hidden: !meta.visible,
            lineCap: style.borderCapStyle,
            lineDash: style.borderDash,
            lineDashOffset: style.borderDashOffset,
            lineJoin: style.borderJoinStyle,
            lineWidth: (borderWidth.width + borderWidth.height) / 4,
            strokeStyle: style.borderColor,
            pointStyle: pointStyle || style.pointStyle,
            rotation: style.rotation,
            textAlign: textAlign || style.textAlign,
            borderRadius: 0,
            datasetIndex: meta.index
        };
    }, this);
}

Then, in your config you need to set the generateLabel function to the one you just generated like so:

const options = {
    plugins: {
        legend: {
            labels: {
                generateLabels: generateLabelsNew,
            },
        },
    },
};

This is effectively over-riding the default label generation function and setting the fill style for the box to a gradient. You use the maxWidth and maxLeft to get the positions of the bounding box of each legend item.

Leave a comment