JSFiddle - React, Tailwind, and code Playground
HTML
<h1>Chart One</h1>
<canvas id="LineChart" height="100"></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('LineChart').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) {
width = chartWidth;
height = chartHeight;
let y = 27; // I want this to be the pixel for value I pass, instead of hard value
// but I can't select y-axis like this:
// var yaxis=y.scales[ 'y-axis-0' ];
// as it says undefined, and if I do like this :
// const { ctx, canvas, scales: { x, y } }=chart;
// var xaxis=x.scales[ 'x-axis-0' ];
// It says chart not defined, which I think is because I am not making this a function and passing chart, and I can't figure out how to do it right.
gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
gradient.addColorStop(y / chartHeight, 'black');
gradient.addColorStop(0.6, 'yellow');
gradient.addColorStop(0.9, 'red');
gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
gradient.addColorStop(y / chartHeight, 'black');
gradient.addColorStop(0.6, 'yellow');
gradient.addColorStop(0.9, 'red');
}
return gradient;
}
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['10', '20', '30', '40', '50'],
datasets: [{
label: 'Hello',
data: ['1', '2', '3', '4', '5'],
backgroundColor: 'rgba(255, 255, 78, 1)',
borderColor: function(context, options) {
const chart = context.chart;
const {
ctx,
chartArea
} = chart;
if (!chartArea) {
return null;
}
return getGradient(ctx, chartArea);
},
}]
},
});