条形图内的文本- chart.js

vhipe2zx  于 2023-03-02  发布在  Chart.js
关注(0)|答案(3)|浏览(235)

我需要使用chart.js将文本写入图表中的条形图

  1. var ctx = document.getElementById("myChart");
  2. var myChart = new Chart(ctx, {
  3. type: 'bar',
  4. data:data,
  5. options: {
  6. scales: {
  7. yAxes: [{
  8. ticks: {
  9. beginAtZero:true
  10. }
  11. }]
  12. }
  13. },
  14. responsive : true,
  15. showTooltips : false,
  16. showInlineValues : true,
  17. centeredInllineValues : true,
  18. tooltipCaretSize : 0,
  19. tooltipTemplate : "<%= value %>"
  20. });

上面的代码不工作...
我需要这样的东西:

rmbxnbpk

rmbxnbpk1#

您是否在代码中定义了var ctx = document.getElementById("myChart");
更新
将以下代码添加到选项对象:

  1. animation: {
  2. onComplete: function () {
  3. var chartInstance = this.chart;
  4. var ctx = chartInstance.ctx;
  5. console.log(chartInstance);
  6. var height = chartInstance.controller.boxes[0].bottom;
  7. ctx.textAlign = "center";
  8. Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
  9. var meta = chartInstance.controller.getDatasetMeta(i);
  10. Chart.helpers.each(meta.data.forEach(function (bar, index) {
  11. ctx.fillText(dataset.data[index], bar._model.x, height - ((height - bar._model.y) / 2));
  12. }),this)
  13. }),this);
  14. }
  15. }

https://jsfiddle.net/h4p8f5xL/
更新2
用具有所需宽度和高度的容器包围画布

  1. <div style="width: 100%; height: 500px">
  2. <canvas id="myChart" width="400" height="400"></canvas>
  3. </div>

并将以下内容添加到选项对象中

  1. // Boolean - whether or not the chart should be responsive and resize when the browser does.
  2. responsive: true,
  3. // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
  4. maintainAspectRatio: false,
展开查看全部
ttvkxqim

ttvkxqim2#

如果要为每个元素呈现居中文本,有一种更简单的方法:

  1. Chart.helpers.each(meta.data.forEach(function (bar, index) {
  2. var centerPoint = bar.getCenterPoint();
  3. ctx.fillText(dataset.data[index], centerPoint.x, centerPoint.y));
  4. }),this)

似乎**“getCenterPoint”在版本2.1.3**(您在示例中使用的)中不可用。我在2.5.0中尝试过,它可以正常工作

pieyvz9o

pieyvz9o3#

到目前为止,有一个插件可以完全处理这种用例!
它被称为chartjs-plugin-datalabels,文档可以在这里找到:https://chartjs-plugin-datalabels.netlify.app/guide/getting-started.html

相关问题