You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Highcharts中为不同折线设置专属渐变填充色?

为Highcharts不同折线设置对应颜色的渐变填充

要实现每个折线使用自身默认颜色的渐变填充,核心是让渐变的起始色动态匹配当前系列的颜色,以下是两种常用方案:

方案1:使用动态函数生成渐变(推荐)

在plotOptions.series.fillColor中传入函数,函数会以当前系列对象作为上下文(this指向当前series),直接获取系列的默认颜色生成渐变:

Highcharts.chart('container', {
    chart: {
        type: 'areaspline'
    },
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    plotOptions: {
        series: {
            fillColor: function() {
                // 获取当前系列的默认颜色
                const seriesColor = this.color;
                return {
                    linearGradient: [0, 0, 0, 300],
                    stops: [
                        [0, seriesColor],
                        // 将当前颜色设置为完全透明作为渐变终点
                        [1, Highcharts.color(seriesColor).setOpacity(0).get('rgba')]
                    ]
                };
            }
        }
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    },
    {
        data: [10, 20, 79.4, 50.2, 40.0, 50.0, 110.6, 90.5, 113.4, 144.1, 75.6, 24.4]
    }]
});

这种方法无需手动为每个系列配置,新增系列时会自动适配,扩展性更强。

方案2:单独为每个系列配置渐变

如果需要对特定系列做自定义调整,可以在每个series对象中单独设置fillColor,指定对应颜色的渐变:

Highcharts.chart('container', {
    chart: {
        type: 'areaspline'
    },
    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    series: [{
        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
        fillColor: {
            linearGradient: [0, 0, 0, 300],
            stops: [
                [0, Highcharts.getOptions().colors[0]],
                [1, Highcharts.color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
            ]
        }
    },
    {
        data: [10, 20, 79.4, 50.2, 40.0, 50.0, 110.6, 90.5, 113.4, 144.1, 75.6, 24.4],
        fillColor: {
            linearGradient: [0, 0, 0, 300],
            stops: [
                [0, Highcharts.getOptions().colors[1]],
                [1, Highcharts.color(Highcharts.getOptions().colors[1]).setOpacity(0).get('rgba')]
            ]
        }
    }]
});

这种方法适合需要对个别系列做特殊渐变设置的场景。

内容的提问来源于stack exchange,提问作者Kvasimodo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:20:48