var ctx = document.getElementById('LineChart').getContext("2d");
let width, height, gradient;
function getGradient(ctx, chartArea, chart) {
const chartWidth = chartArea.right - chartArea.left;
const chartHeight = chartArea.bottom - chartArea.top;
if (gradient === null || width !== chartWidth || height !== chartHeight) {
width = chartWidth;
height = chartHeight;
let y2 = 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.
const { scales: { x, y } } = chart;
console.log(x.getPixelForValue(20), x.getPixelForValue(4))
gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
gradient.addColorStop(y2 / chartHeight, 'black');
gradient.addColorStop(0.6, 'yellow');
gradient.addColorStop(0.9, 'red');
gradient = ctx.createLinearGradient(0, chartArea.bottom, 0, chartArea.top);
gradient.addColorStop(y2 / 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, chart);
},
}]
},
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.