When I generate line chart in fullscreen window, shown colors are in declared radius, however when I try to resize window, chart is resized properly however gradient colors are messed up. I try to solve this problem via listeners, however it doesn't work.
Anyone got ideas?
Here is my code:
var chrt = document.getElementById("mycanvas");
var ctx = chrt.getContext("2d");
var gradient = ctx.createLinearGradient(300, 0, 300, 600);
gradient.addColorStop(0, 'black');
gradient.addColorStop(0.25, 'red');
gradient.addColorStop(0.5, 'orange');
gradient.addColorStop(0.75, 'yellow');
gradient.addColorStop(1, 'green');
mycanvas.addEventListener("resize", gradient_declaration);
function gradient_declaration() {
var w = mycanvas.innerWidth;
var h = mycanvas.innerHeight;
if (gradient) { gradient.destroy(); } else {
var gradient = ctx.createLinearGradient(w / 2, 0, w / 2, h);
gradient.addColorStop(0, 'black');
gradient.addColorStop(0.25, 'red');
gradient.addColorStop(0.5, 'orange');
gradient.addColorStop(0.75, 'yellow');
gradient.addColorStop(1, 'green');
}
}
It's probably too late for you, but I came across the same issue. the way I solved it was to create an inline plugin that will recalculate the gradient everytime the layout changes eg (resizing, data changing, etc)
var chart2 = new Chart(ctx, {
plugins: [
{
id: "responsiveGradient",
afterLayout: function(chart, options) {
var scales = chart.scales;
// create a linear gradient with the dimentions of the scale
var color = chart.ctx.createLinearGradient(
scales["x-axis-0"].left,
scales["y-axis-0"].bottom,
scales["x-axis-0"].right,
scales["y-axis-0"].top
);
// add gradients stops
color.addColorStop(0, "black");
color.addColorStop(0.25, "red");
color.addColorStop(0.5, "orange");
color.addColorStop(0.75, "yellow");
color.addColorStop(1, "green");
// changes the background color option
chart.data.datasets[0].backgroundColor = color;
}
}
]
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With