LineChart colored segmetns

by bairog

HTML

<div id="chartDiv"><canvas id="chart"></canvas></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>

JavaScript

function isObject(value) {
    return value !== null && Object.prototype.toString.call(value) === '[object Object]';
}

function valueOrDefault(value, defaultValue) {
    return typeof value === 'undefined' ? defaultValue : value;
}

const numberOrZero = v => +v || 0;

function _readValueToProps(value, props) {
    const ret = {};
    const objProps = isObject(props);
    const keys = objProps ? Object.keys(props) : props;
    const read = isObject(value)
        ? objProps
            ? prop => valueOrDefault(value[prop], value[props[prop]])
            : prop => value[prop]
        : () => value;

    for (const prop of keys) {
        ret[prop] = numberOrZero(read(prop));
    }
    return ret;
}

function toTRBL(value) {
    return _readValueToProps(value, { top: 'y', right: 'x', bottom: 'y', left: 'x' });
}

function toPadding(value) {
    const obj = toTRBL(value);

    obj.width = obj.left + obj.right;
    obj.height = obj.top + obj.bottom;

    return obj;
}

function generateLabels(chart) {
    const datasets = chart.data.datasets;
    const { labels: { usePointStyle, pointStyle, textAlign, color, boxWidth, boxHeight, font } } = chart.legend.options;

    return chart._getSortedDatasetMetas().map((meta) => {
        const style = meta.controller.getStyle(usePointStyle ? 0 : undefined);
        const borderWidth = toPadding(style.borderWidth);

        const labelFont = (font != null) ? font : Chart.defaults.font;
        const labelBoxHeight = (boxHeight != null) ? boxHeight : labelFont.size;

        var gradient = chart.ctx.createLinearGradient(0, 0, boxWidth, labelBoxHeight);
        gradient.addColorStop(0.33, "rgb(75, 192, 192)");
        gradient.addColorStop(0.33, "rgb(192,75,75)");
        gradient.addColorStop(0.66, "rgb(192,75,75)");
        gradient.addColorStop(0.66, "rgb(0,0,0,0.2)");

        return {
            text: '!!!TEST!!!',//datasets[meta.index].label,
            fillStyle: gradient,
            fontColor: color,
           ...