Chartjs-How can I apply a linear gradient to fill in chart.js

0👍

Solution:

backgroundColor: (context) => {
            const ctx = context.chart.ctx;
            const gradient = ctx.createLinearGradient(0, 0, 0, 200);
            gradient.addColorStop(0, "rgba(127,86,217,0.1)");
            gradient.addColorStop(1, "rgba(127, 86, 217, 0)");
            return gradient;
        }

0👍

Gradients on canvas are created using canvas.createLinearGradient()

You’d need to do something like this for backgroundColor:

datasets: [
    {
      label: 'Dataset 1',
      data: [420, 430, 680, 560, 790, 240, 395, 830, 810, 430, 500, 700],
      borderColor: '#7F56D9',
      borderWidth: 2,
      fill: 'start',
      backgroundColor: (ctx) => {
        const canvas = ctx.chart.ctx;
        const gradient = canvas.createLinearGradient(0, -160, 0, 120);

        gradient.addColorStop(0, '#7F56D9');
        gradient.addColorStop(1, '#fff');

        return gradient;
      },
    },
  ],

enter image description here

It’s about as close as I could get to your image.

CSS linear-gradient and canvas createLinearGradient aren’t related and have no 1:1 translation (as far as I know), so you’ll just need to play around with the numbers until you get a gradient close to what you want.

Leave a comment