DEV Community

Ricardo Nishimura
Ricardo Nishimura

Posted on • Updated on

Chartjs with Gradient Background

How to add a gradient background for the entire Chart.js and not just for the dataset, that was my first question when I started to play with it, so here I am...

Alt Text

Chart Plugins

The Chartjs Plugins are the most efficient way to customize or change the default behavior of a chart. They have been introduced at version 2.1.0 (global plugins only) and extended at version 2.5.0 (per chart plugins and options).

With a custom plugin we can draw a custom background implementing the function "beforeDraw".

There were some changes to the plugin interface in the ChartJs version 3, this code example was updated to reflect it, thanks to Hung Tran for pointing me out.

The following plugin draws a custom gradient in the chart background:

var GradientBgPlugin = {
  beforeDraw: function(chart, args, options) {
    const ctx = chart.ctx;
    const canvas = chart.canvas;
    const chartArea = chart.chartArea;

    // Chart background
    var gradientBack = canvas.getContext("2d").createLinearGradient(0, 0, 0, 250);
    gradientBack.addColorStop(0, "rgba(60, 174, 163, 0.7)");
    gradientBack.addColorStop(0.5, "rgba(255, 255, 255, 0)");
    gradientBack.addColorStop(1, "rgba(32, 99, 155, 0.7)");

    ctx.fillStyle = gradientBack;
    ctx.fillRect(chartArea.left, chartArea.bottom,
      chartArea.right - chartArea.left, chartArea.top - chartArea.bottom);
  }
};

Enter fullscreen mode Exit fullscreen mode

Then insert the custom plugin in the Chart configuration and voilà:

Top comments (4)

Collapse
 
hungtran11 profile image
Hung Tran

Thanks! It worked for me after changing two lines:
const ctx = chartInstance.ctx;
const canvas = chartInstance.canvas;

Collapse
 
ricnish profile image
Ricardo Nishimura

Thanks, it looks like the version 3 has changed the plugin interface, I will try to update the example.

Collapse
 
zylascope profile image
Geoff Williams

Thanks.

Collapse
 
ashiqdey profile image
Ashiq Dey

how to add gradient background with chart.js in react?