如何将用Chart.js创建的折线图的线条设置为渐变?

sh7euo9m  于 11个月前  发布在  Chart.js
关注(0)|答案(1)|浏览(219)


的数据
我试图使用Chart.js在图像中获取图表。但我找不到如何制作线条渐变。我想做的是在线条向上时使用rgba(249,65,68,1)颜色,在线条向下时使用rgba(51,51,51,1)颜色。

<script>
document.addEventListener("DOMContentLoaded", function () {

    var dataValues = [18, 20, 18, 15, 12, 8, 11, 22];

    var data = {
        labels: Array.from({ length: dataValues.length }, (_, index) => ""),
        datasets: [
            {
                label: "",
                borderColor: "rgba(249, 65, 68, 1)",
                data: dataValues,
                pointBackgroundColor: "rgba(249, 65, 68, 1)",
                fill: false,
            },
        ],
    };

    var ctx = document.getElementById("timeChart").getContext("2d");
    var myLineChart = new Chart(ctx, {
        type: "line",
        data: data,
        options: {
            datasetFill: true,
            showTooltips: false,
            maintainAspectRatio: false,
            responsive: true,
            plugins: {
                legend: {
                    display: false,
                },
            },
        },
    });
});

字符串

kjthegm6

kjthegm61#

根据文档,您必须添加此功能:

let width, height, gradient;
function getGradient(ctx, chartArea) {
  const chartWidth = chartArea.right - chartArea.left;
  const chartHeight = chartArea.bottom - chartArea.top;
  if (!gradient || width !== chartWidth || height !== chartHeight) {
    // Create the gradient because this is either the first render
    // or the size of the chart has changed
    width = chartWidth;
    height = chartHeight;
    gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
    gradient.addColorStop(0, "rgba(51, 51, 51, 1)");
    gradient.addColorStop(0.5, "rgba(249, 65, 68, 1)");
  }

  return gradient;
}

字符串
然后你会在数据集内返回它:

datasets: [
    {
      label: 'Dataset 1',
      data: Utils.numbers(NUMBER_CFG),
      borderColor: function(context) {
        const chart = context.chart;
        const {ctx, chartArea} = chart;

        if (!chartArea) {
          // This case happens on initial chart load
          return;
        }
        return getGradient(ctx, chartArea);
      },
    },
  ]


下面是这个例子的link

相关问题