javascript - Chart.js 3.3.0 - 在图表顶部绘制文本
问题描述
我对 JS 很陌生,我正在使用 Chart.js v3 构建图表。我正在寻找一种将文本位放置在图表上特定 x,y 坐标处的方法,独立于任何数据点。我已经看到了一些针对以前版本的 chart.js 的解决方案,比如这里的这个,但一直无法让它工作。
有什么方法可以通过chart.js 实现这一点,还是我必须手动将文本元素添加到画布?
解决方案
最好的办法是编写一个自定义插件,您可以在其中将文本放在画布上,chart.js 不提供开箱即用的此功能
例子:
const customText = {
id: 'customText',
afterDraw: (chart, args, options) => {
const {
ctx,
canvas
} = chart;
textObjects = options.text;
if (textObjects.length === 0) {
return;
}
textObjects.forEach((textObj) => {
ctx.save();
ctx.textAlign = textObj.textAlign || 'center';
ctx.font = `${textObj.size || '20px'} ${textObj.font || 'Arial'}`;
ctx.fillStyle = textObj.color || 'black'
ctx.fillText(textObj.text, textObj.x, textObj.y)
ctx.restore();
})
}
}
const 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: {
plugins: {
customText: {
text: [{
text: 'Lorem ipsum',
x: 300,
y: 150,
textAlign: 'center',
size: '30px',
color: 'black',
font: 'Arial black'
},
{
text: 'Lorem ipsum2',
x: 300,
y: 250,
textAlign: 'center',
color: 'red',
font: 'Arial black'
}
]
}
}
},
plugins: [customText]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.0/chart.js"></script>
</body>
推荐阅读
- java - 没有获得在服务器上存储我的文件的正确路径
- javascript - 如何在 javascsript 中隐藏打印对话框
- javascript - 将数字的因数返回到空数组中的函数
- vue.js - vue - 插值 html 值
- php - 我想将一个数组从 php 文件发送到 smarty 中的 .tpl 文件
- python - 是否可以在 cv2 窗口上激活/设置焦点?
- javascript - 使用 Web Audio API 从 HTML5 视频中访问缓冲的音频数据
- swift - 如何使用 swift 查找下一个工作日或周末?
- pycharm - 从 CLI 在项目中打开 PyCharm
- php - Laravel Livewire 使用重定向将变量数据从一个组件传递到另一个组件