如何在 chart.js 中应用渐变颜色?

2022-01-22 00:00:00 reactjs javascript css chart.js typescript

我正在使用 chart.js 库制作折线图,在这里我想将线条的颜色更改为渐变色.

I am making a line chart using chart.js library and here I would like to change the color of the line to gradient color.

我尝试过的代码,

  const gradientFill = ctx.createLinearGradient(500, 0, 100, 0);
  gradientFill.addColorStop(0, "#80b6f4");
  gradientFill.addColorStop(1, "#f49080");

并将其添加到数据集中,例如,

And added it in dataSets like,

datasets: [
  {
    .
    .
    .
    .
    backgroundColor: gradientFill,
    .
    .
  }
]

但我看不到变化,仍然只显示一些灰色线条而不是渐变.

But I couldn't see the changes and still some gray color line only gets displayed instead of gradient.

工作示例:

尝试添加 borderColor : gradientFill 但这也不起作用.

Tried adding borderColor : gradientFill but that also doesn't work.

要求:要求是我需要有类似 https://i.stack.imgur.com/lKGqT.png

请帮我把颜色改成渐变色.

Kindly please help me to change the color to gradient color.

推荐答案

由于您的 useEffect 钩子,您的渐变不适用,在此钩子中您使用 formatData<再次设置数据/code> 函数,但只传递数据,没有 canvasGradient.所以你也需要通过它.

Your gradient does not apply because of your useEffect hook, in this hook you set the data again with your formatData function but only pass the data and no canvasGradient. So you will need to pass that too.

查看第 108 行和第 109 行,注释掉它可以正常工作,因此您需要在此处重新创建渐变或在更高级别上创建它,以便您只创建一次.https://codesandbox.io/s/chart-js-react-typescript-forked-dxlj7?file=/src/App.tsx

See with lines 108 and 109 commented out it works fine, so you will need to either recreate the gradient there or create it on a higher level so you only create it once. https://codesandbox.io/s/chart-js-react-typescript-forked-dxlj7?file=/src/App.tsx

更新为不同的方法,在您的 formatData 函数中为 backgroundColor 使用三元运算符来检查如果不采用当前 backgroundColor 是否给出画布渐变

Updated to different method, in your formatData function for the backgroundColor use ternary operator to check if canvas gradient is given if not take the current backgroundColor

相关文章