Multiple times running function chartjs
by Jesper02
HTML
<canvas id="myChart" width="200" height="200"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.0/chart.min.js" integrity="sha512-asxKqQghC1oBShyhiBwA+YgotaSYKxGP1rcSYTDrB0U6DxwlJjU59B67U8+5/++uFjcuVM8Hh5cokLjZlhm3Vg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2"></script>
JavaScript
var ctx = document.getElementById('myChart').getContext('2d');
let width, height, gradient;
function getGradient(ctx, chartArea) {
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, "rgb(54, 162, 235)");
gradient.addColorStop(0.5, "rgb(255, 205, 86)");
gradient.addColorStop(1, "rgb(255, 99, 132)");
}
return gradient;
}
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: function(context) {
const chart = context.chart;
const {ctx, chartArea} = chart;
if (!chartArea) {
// This case happens on initial chart load
return null;
}
return getGradient(ctx, chartArea);
},
borderWidth: 1
}]
},
options: {
responsive: false,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
}
},
}
});