Gradients

There is no native support in Chart.js for gradients, but they are fairly easy to generate with Canvas. The problem is that a gradient has an absolute position in a Canvas object, while your chart may be responsive. If the chart is resized, the gradient has to be recalculated and the chart updated.

One way to deal with this is to call a gradient function as soon as the chart is created and every time the window is resized, feeding the Canvas gradient function with the dimensions of the area where the gradient will be applied. We can do this with a callback and the Chart.js update() function.

A gradient in Canvas is created with the following function:

canvasContext.createLinearGradient(x0, y0, x1, y1);

The gradient contains the equation of a perpendicular line. To create a linear gradient that varies along the axis, we need to draw the line from the bottom of the chart to the top. That means that x0 = x1 = 0, y1 is the bottom of the chart, and y0 is the top. If we write a function that receives a chart instance, we can retrieve that information from scales["y-axis-0"].top and scales["y-axis-0"].bottom. Here is a function for drawing gradients for the background colors and a line chart with two datasets (Colors/colors-3-gradient.html):

function drawGradient(chart) {
const x0 = 0;
const y0 = chart.scales["y-axis-0"].top;
const x1 = 0;
const y1 = chart.scales["y-axis-0"].bottom;

const gradient1 = chart.ctx.createLinearGradient(x0, y0, x1, y1);
gradient1.addColorStop(0, 'hsla(60,100%,70%,.4)');
gradient1.addColorStop(1, 'hsla(0,100%,25%,.8)');

const gradient2 = chart.ctx.createLinearGradient(x0, y0, x1, y1);
gradient2.addColorStop(0, 'hsla(300,100%,70%,.4)');
gradient2.addColorStop(1, 'hsla(240,100%,25%,.8)');

chart.data.datasets[0].backgroundColor = gradient1;
chart.data.datasets[1].backgroundColor = gradient2;
}

You have to call that function as soon as the chart is created and then invoke update() to redraw the chart. After each resize, call it again. This can be done automatically using the onComplete() animation callback, as shown in the following code:

const data = {
labels: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
datasets: [
{
label: 'Week 1',
data: [2, 5, 2, 0, 20, 48, 51],
borderColor: 'red'
},{
label: 'Week 2',
data: [44, 36, 13, 40, 40, 9, 3],
borderColor: 'blue'
}
]
};

const chart = new Chart('canvas', {
type: 'line',
data: data,
options: {
animation: {
onComplete: function(context) {
drawGradient(context.chart);
}
}
}
});
drawGradient(chart);
chart.update();

The final result is shown in the following screenshot:

Line chart using gradients as backgroundColor for each dataset. Code: Colors/colors-3-gradient.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset