React chartjs:背景渐变未出现

hof1towb  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(167)

尝试为折线图创建渐变背景。我试图实施的解决方案不起作用。见屏幕截图:

我实现了canvas的codeLinearGradient(),但没有用。我还能做错什么编辑:我添加了所有导入,包括Filler。这样还是不行

import { Line } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler,
  ScriptableContext,
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
);

function Linechart() {
  const labels = ["January", "February", "March", "April", "May", "June"];

  const dataLineChart = {
    labels: labels,
    datasets: [
      {
        backgroundColor: (context: ScriptableContext<"line">) => {
          const ctx = context.chart.ctx;
          const gradient = ctx.createLinearGradient(0, 0, 0, 200);
          gradient.addColorStop(0, "rgba(250,174,50,1)");
          gradient.addColorStop(1, "rgba(250,174,50,0)");
          return gradient;
        },
        label: "UST",
        fill: "start",
        borderColor: "#8E95DF",
        data: [0, 10, 5, 2, 20, 30, 45],
      },
    ],
  };

  const configLineChart = {
    type: "line",
    dataLineChart,
    elements: {
      line: {
        tension: 0.35,
      },
    },
    plugins: {
      filler: {
        propagate: false,
      },
    },
  };

  return (
    <div>
      <div className="px-5 py-3">Fund Profits</div>
      <Line data={dataLineChart} options={configLineChart}></Line>
    </div>
  );
}

export default Linechart;

编辑:当将const gradient = ctx.createLinearGradient(0, 0, 0, 200);更改为const gradient = ctx.createLinearGradient(0, 0, 0, 500);时,我的渐变变得可见。有人能解释一下这个值是如何工作的吗?

7hiiyaii

7hiiyaii1#

200和500是指图中的像素x/y位置。它允许您决定要在哪个轴位置开始/停止渐变。以下是告诉你每个值背后含义的文档:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createLinearGradient
我有我的线性梯度从顶部的颜色到底部的透明。下面是我的实现:

const gradient = context.chart.ctx.createLinearGradient(0, 0, 0, context.chart.chartArea.height);

在这个例子中,我用我的context.chart.chartArea.height来告诉我画布的高度,我让它连接到顶部,这样渐变就覆盖了整个背景(即超高的值会有一个明亮的颜色,而低的值会在填充上是透明的)。

相关问题