我正在尝试在ChartJs图表的插件下创建线性渐变。不幸的是,我收到一个错误消息:
无法在'CanvasRenderingContext2D'上执行'createLinearGradient':提供的双精度值是非限定的。
我正在尝试在插件中添加我的linearGradient,因为我希望该渐变在每个比例上对齐。
这里是我在下面尝试的内容
barChart = new Chart(elem, {
plugins: [
{
id: "responsiveGradient",
afterLayout: function(chart, options) {
var scales = chart.scales;
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;
}
}
],
type: 'horizontalBar',
data: datasets,
options: {
maintainAspectRatio: false,
tooltips: { enabled: false },
title: {
display: false,
},
responsive: true,
legend: {
display: false,
position: "top"
},
scales: {
xAxes: [{
ticks: {
beginAtZero: false,
min:0.5,
max:0.8,
maxTicksLimit: 6,
},
scaleLabel: {
display: false
},
barThickness: 5,
gridLines: {
display: false,
zeroLineColor: "transparent",
}
}],
yAxes: [{
barThickness: 5,
ticks: {
maxTicksLimit: 6,
padding: 15,
},
gridLines: {
drawTicks: false,
display: false
}
}]
}
},
});
plugins.afterLayout
函数的最后一行。没有诸如chart.data
的对象,请改用chart.config.data
。// chart.data.datasets[0].backgroundColor = color; // replace this line
chart.config.data.datasets[0].backgroundColor = color;
请在下面查看您的修改后的代码(我必须对您的数据进行假设)。const datasets = { labels: ['A', 'B', 'C'], datasets: [{ label: 'data', data: [0.6, 0.7, 0.8], barThickness: 5 }] }; new Chart("myChart", { plugins: [{ id: "responsiveGradient", afterLayout: (chart, options) => { var scales = chart.scales; var color = chart.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.config.data.datasets[0].backgroundColor = color; } }], type: 'horizontalBar', data: datasets, options: { maintainAspectRatio: false, tooltips: { enabled: false }, title: { display: false, }, responsive: true, legend: { display: false, position: "top" }, scales: { xAxes: [{ ticks: { beginAtZero: false, min: 0.5, max: 0.8, maxTicksLimit: 6, }, scaleLabel: { display: false }, gridLines: { display: false, zeroLineColor: "transparent", } }], yAxes: [{ ticks: { maxTicksLimit: 6, padding: 15, }, gridLines: { drawTicks: false, display: false } }] } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script> <canvas id="myChart" height="100"></canvas>