我想在所有图表绘图后面的 ChartJS 中心添加一个信息背景文本。除了使用此处所示的图像之外,还有其他方法吗:How can i add an image as background in Chartjs? ?
问候,
最佳答案
您可以扩展Chart
的draw()
函数来向图表添加文本。然后,您可以通过计算图表中间的 x 和 y 值或指定它们来控制文本的位置,具体取决于图表的呈现方式:
let myLineExtend = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw: function() {
myLineExtend.apply(this, arguments);
// text styles below
this.chart.chart.ctx.textAlign = "center"
this.chart.chart.ctx.font = "20px Arial black";
this.chart.chart.ctx.fillText("Lorem Ipsum Blah Blah", 300, 150) // text, x-pos, y-pos
}
});
这是一个演示这一点的片段:
let myLineExtend = Chart.controllers.line.prototype.draw;
let options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
}
}
let ctx = document.getElementById('container').getContext('2d');
Chart.helpers.extend(Chart.controllers.line.prototype, {
draw: function() {
myLineExtend.apply(this, arguments);
this.chart.chart.ctx.textAlign = "center"
this.chart.chart.ctx.font = "20px Arial black";
this.chart.chart.ctx.fillText("Lorem Ipsum Blah Blah", 300, 150)
}
});
new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>
<body>
<canvas id="container" width="600" height="400"></canvas>
</body>
关于javascript - 在 ChartJS 中添加背景文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57567325/