如何使用Chart.js将图表的背景颜色设置为渐变

mec1mxoz  于 2022-11-07  发布在  Chart.js
关注(0)|答案(1)|浏览(218)

我正在React中尝试使用Chart.js制作一个折线图。我没有使用DOM来创建和到达画布。我可以安排背景颜色,但我只想让它成为渐变。我该怎么做呢?

我的代码如下:

import React from "react";
import { Line } from "@reactchartjs/react-chart.js";

const data = {
  labels: ["day1", "day2", "day3", "day4", "day5", "day6"],
  datasets: [
    {
      label: "Your BMI",
      data: [28.3, 28, 27, 27.6, 25, 25.6],
      fill: true,
      backgroundColor: "rgba(10,10,10,.2)",
      borderColor: "rgba(152,222,217,0.2)"
    }
  ]
};

const options = {
  scales: {
    yAxes: [
      {
        ticks: {
          beginAtZero: true
        }
      }
    ]
  }
};

const LineChart = () => (
  <>
    <Line data={data} options={options} />
  </>
);

export default LineChart;

output

68bkxrlz

68bkxrlz1#

您可以使用画布的“createLinearGradient”方法。
文件:https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradienthttps://developer.mozilla.org/en-US/docs/Web/API/CanvasGradient/addColorStop
示例:https://codepen.io/alexgill/pen/MWbjXOP

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var gradient = ctx.createLinearGradient(0, 0, 0, 400);
gradient.addColorStop(0, 'rgba(10,10,10,.2)');   
gradient.addColorStop(1, 'rgba(255,255,255,1)');

const data = {
  labels: ["day1", "day2", "day3", "day4", "day5", "day6"],
  datasets: [
    {
      label: "Your BMI",
      data: [28.3, 28, 27, 27.6, 25, 25.6],
      backgroundColor : gradient,
      borderColor: "rgba(152,222,217,0.2)"
    }
  ]
};

相关问题