Tom*_*mek 3 javascript charts gradient responsive
当我在全屏窗口中生成折线图时,显示的颜色在声明的半径中,但是当我尝试调整窗口大小时,图表会正确调整大小,但渐变颜色会混乱.我试图通过听众解决这个问题,但它不起作用.
有人有想法吗?
这是我的代码:
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');
}
}
Run Code Online (Sandbox Code Playgroud)
对你来说可能为时已晚,但我遇到了同样的问题.我解决它的方法是创建一个内联插件,每次布局更改时重新计算渐变,例如(调整大小,数据更改等)
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;
}
}
]
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
996 次 |
最近记录: |