Home > database >  How to apply gradient color in chart.js?
How to apply gradient color in chart.js?

Time:12-25

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.

Code I have tried,

  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.

Working Example:

Edit Chart.js React Typescript (forked)

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

Requirement: Requirement is that I need to have a gradient line similar like https://i.stack.imgur.com/lKGqT.png

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

CodePudding user response:

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.

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

Edit:

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

CodePudding user response:

you can use borderColor : 'Red' in the datasets. see below code

datasets: [
      {
        pointBorderWidth: 10,
        pointHoverRadius: 10,
        pointHoverBorderWidth: 1,
        pointRadius: 3,
        fill: "start",
        backgroundColor: gradientFill,
        borderWidth: 4,
        borderColor : 'Red',   //  New line added
        data
      }
    ]
  • Related