Chartjs-Chartjs – How to use differente color if value is lower than previous value?

0👍

You could achieve the wanted result by attributing the colors with a function on a gradientStroke.

Basically you can create a gradient line in Chart.js :

var ctx = document.getElementById('myChart').getContext("2d");
var gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
gradientStroke.addColorStop(0, "#80b6f4");
gradientStroke.addColorStop(1, "#f49080");

In the case above you would end up with a gradient from red (#80b6f4) to blue (#f49080) but you can simply divide 1 (position of the point) by the number of points you have.

For example, if you have 5 points you would do:

var ctx = document.getElementById('myChart').getContext("2d");
var gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
gradientStroke.addColorStop(0, "#80b6f4");
gradientStroke.addColorStop(0.25, "#f49080");
gradientStroke.addColorStop(0.5, "#f49080");
gradientStroke.addColorStop(0.75, "#80b6f4");
gradientStroke.addColorStop(1, "#f49080");

Create a function and use loops to make your solution scalable.

Leave a comment