1👍
✅
You need to define this line let width, height, gradient;
within your function so its bound to the function and wont get overriden then it works just fine:
const getGradient = (ctx, chartArea, start_color, stop_color) => {
let width, height, gradient;
const chartWidth = chartArea.right - chartArea.left;
const chartHeight = chartArea.bottom - chartArea.top;
if (gradient === null || width !== chartWidth || height !== chartHeight) {
// Create the gradient because this is either the first render
// or the size of the chart has changed
width = chartWidth;
height = chartHeight;
gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
gradient.addColorStop(0, stop_color);
gradient.addColorStop(1, start_color);
}
return gradient;
}
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: function(context) {
const chart = context.chart;
const {
ctx,
chartArea
} = chart;
if (!chartArea) {
return null;
}
return getGradient(ctx, chartArea, "rgba(182, 86, 235, 1)", "rgba(182, 86, 235, 0.66)");
}
},
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: function(context) {
const chart = context.chart;
const {
ctx,
chartArea
} = chart;
if (!chartArea) {
return null;
}
return getGradient(ctx, chartArea, "rgba(244, 102, 235, 1)", "rgba(244, 102, 235, 0.66)");
}
}
]
},
options: {
}
});
<script src="https://npmcdn.com/chart.js@3.9.1/dist/chart.min.js"></script>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"></canvas>
</div>
Source:stackexchange.com