[英]Change label text of react chartjs into image
我有一個由react-chartjs
組成的react-chartjs
。 現在它有一個文本標簽。 我想要的是將圖像放在標簽文本的位置。 我試圖在標簽中添加一個圖像,但不是顯示圖像,而是顯示該圖像的路徑。
圖形數據狀態變量
graphData: {
labels: ['4 A.M', '5 A.M', '6 A.M', '7 A.M', '8 A.M', '9 A.M', '10 A.M', '11 A.M', '12 P.M', '1 P.M', '2 P.M', '3 P.M', '4 P.M', '5 P.M', '6 P.M', '7 P.M', '8 P.M', '9 P.M', '10 P.M', '11 P.M', '12 A.M', '1 A.M', '2 A.M', '3 A.M'],
datasets: [{
label: User, //User image is imported in this component
backgroundColor: "#69c9e0",
borderColor: '#69c9e0',
borderWidth: 2,
lineTension: 0.1,
fill: true,
data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
{
label: User, //User image is imported in the label
backgroundColor: "#f8a046",
borderColor: '#f8a046',
borderWidth: 2,
lineTension: 0.1,
fill: true,
data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
}
]
}
這可以通過插件核心 API來完成。 API 提供了可用於執行自定義代碼的不同鈎子。 在您的情況下,您可以使用afterDraw
掛鈎直接在畫布上使用CanvasRenderingContext2D
繪制圖像(圖標)而不是刻度標簽。
該插件將定義如下:
const plugins = [{
afterDraw: chart => {
let ctx = chart.chart.ctx;
ctx.save();
let xAxis = chart.scales['x-axis-0'];
let yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
let x = xAxis.getPixelForTick(index);
let image = new Image();
image.src = ..., // provide the image URL
ctx.drawImage(image, x - 12, yAxis.bottom + 10);
});
ctx.restore();
}];
然后告訴Bar
元素要使用的plugin
。
<Bar
...
plugins={plugins}
/>
還可以通過在圖表options
定義layout.padding.bottom
在圖表底部添加一些額外的空間,否則文本將不可見。
layout: {
padding: {
bottom: 60
}
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.