我试图在图表上方但在图表边框后面显示网格线,但我没有找到任何解决方案。
我使用 z 在图表上方显示网格线并将网格线颜色更改为背景颜色。这隐藏了图表外的网格线,但我仍然在图表边框上有一条恼人的线,我不知道如何隐藏......
这就是我要说的:
我的配置:
this.myChart = new Chart(this.canvasRef.current, {
type: "line",
options: {
title: { display: false },
legend: { display: false },
elements: {
point: {
radius: 0,
},
},
scales: {
xAxes: [
{
gridLines: {
drawBorder: false,
display: true,
color: "#f8f8f8",
lineWidth: 1,
z: 1,
drawTicks: false,
zeroLineColor: "#f8f8f8",
},
},
],
yAxes: [
{
gridLines: {
drawBorder: false,
display: false,
},
ticks: {
display: false,
},
},
],
},
},
data: {
labels: [2.7, 3.7, 5.7, 6.7, 7.7, 8.8, 9.9],
datasets: [
{
data: [86, 114, 106, 106, 107, 111, 133],
borderColor: "#3e95cd",
backgroundColor: "rgba(63, 121, 230, 0.4)",
fill: true,
},
],
},
});
最佳答案
您可以使用 Plugin Core API 将自己的网格线直接绘制到 canvas
上。它提供了可用于执行自定义代码的不同钩子(Hook)。您可以使用 afterDraw
钩子(Hook)绘制垂直线,直至数据集中包含的各个点,但停在该线下方。
ctx.lineTo(x, yTop + 2);
请在下面查看您修改后的代码。new Chart('myChart', {
type: "line",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
ctx.save();
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
var yTop = yAxis.getPixelForValue(chart.config.data.datasets[0].data[index]);
ctx.strokeStyle = '#f8f8f8';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x, yAxis.bottom);
ctx.lineTo(x, yTop + 2);
ctx.stroke();
});
ctx.restore();
}
}],
data: {
labels: [2.7, 3.7, 5.7, 6.7, 7.7, 8.8, 9.9],
datasets: [{
data: [86, 114, 106, 106, 107, 111, 133],
borderColor: "#3e95cd",
backgroundColor: "rgba(63, 121, 230, 0.4)",
fill: true
}]
},
options: {
legend: {
display: false
},
elements: {
point: {
radius: 0
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
}
}],
yAxes: [{
gridLines: {
drawBorder: false,
display: false
},
ticks: {
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>
关于javascript - 网格线后面的边框,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63013026/