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

如何为Chart.js堆叠柱状图的每个数据集设置独立渐变

实现Chart.js堆叠柱状图的分段独立渐变

你当前的问题是渐变基于整个画布高度创建,导致整根柱子共用一个渐变范围。要让每个堆叠分段拥有独立渐变,需要利用Chart.js提供的元素上下文参数,针对每个分段的实际绘制位置和高度生成渐变。

修改后的完整代码

<!DOCTYPE html>
<html>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<body>
<canvas id="myChart" width="800" height="400"></canvas>
<script>
    var ctx = document.getElementById('myChart').getContext("2d")
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL"],
            datasets: [{
                label: "Data 1",
                fill: true,
                backgroundColor: function(context) {
                    // 获取当前分段的实际绘制位置和高度
                    const { y, height } = context.raw;
                    // 基于分段的上下边界创建垂直渐变
                    const gradientFill = ctx.createLinearGradient(0, y, 0, y + height);
                    gradientFill.addColorStop(0.0, '#003399');
                    gradientFill.addColorStop(1.0, '#F8F804');
                    return gradientFill;
                },
                borderWidth: 4,
                data: [100, 120, 150, 170, 180, 170, 160]
            },
            {
                label: "Data 2",
                fill: true,
                backgroundColor: function(context) {
                    const { y, height } = context.raw;
                    const gradientFill = ctx.createLinearGradient(0, y, 0, y + height);
                    // 可给第二个数据集设置不同渐变颜色增强区分
                    gradientFill.addColorStop(0.0, '#0066CC');
                    gradientFill.addColorStop(1.0, '#FFDD00');
                    return gradientFill;
                },
                borderWidth: 4,
                data: [110, 120, 150, 170, 180, 170, 160]
            }]
        },
        options: {
            legend: {
                position: "bottom"
            },
            scales: {
                y: {
                    stacked: true,
                },
                x: {
                    stacked: true,
                }
            }
        }
    });
</script>
</body>
</html>

关键说明

  • backgroundColor的回调函数接收context参数,其中context.raw包含当前分段的绘制坐标(y是分段顶部的画布y坐标,height是分段的像素高度)
  • 渐变的起始点设为分段顶部(0, y),结束点设为分段底部(0, y + height),确保渐变仅作用于当前分段范围
  • 不同数据集可设置差异化的渐变颜色,提升分段辨识度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 01:54:59