如何在ChartJS長條圖上顯示文字?
P粉578343994
P粉578343994 2023-10-23 14:58:30
0
2
591

我需要使用chart.js 將文字寫入圖表中的長條圖中

var ctx = document.getElementById("myChart");
 var myChart = new Chart(ctx, {
     type: 'bar',
     data:data,
     options: {           
         scales: {
             yAxes: [{
                 ticks: {
                     beginAtZero:true
                 }
             }]
         }
     },
     responsive : true,
     showTooltips : false,
     showInlineValues : true,
     centeredInllineValues : true,
     tooltipCaretSize : 0,
     tooltipTemplate : "<%= value %>"
 });

上面的程式碼不起作用...

我需要這樣的東西:

P粉578343994
P粉578343994

全部回覆(2)
P粉803527801

如果您想為每個元素呈現居中文本,有一個更簡單的方法:

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

似乎'getCenterPoint'在版本2.1.3中不可用(您在範例中使用的)。我用 2.5.0 嘗試過,它可以工作

P粉362071992

將此程式碼新增到您的選項物件中:

animation: {
  onComplete: function () {
    var chartInstance = this.chart;
    var ctx = chartInstance.ctx;
    console.log(chartInstance);
    var height = chartInstance.controller.boxes[0].bottom;
    ctx.textAlign = "center";
    Chart.helpers.each(this.data.datasets.forEach(function (dataset, i) {
      var meta = chartInstance.controller.getDatasetMeta(i);
      Chart.helpers.each(meta.data.forEach(function (bar, index) {
        ctx.fillText(dataset.data[index], bar._model.x, height - ((height - bar._model.y) / 2));
      }),this)
    }),this);
  }
}

https://jsfiddle.net/h4p8f5xL/

#更新2

用具有所需寬度和高度的容器包圍畫布

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

並將以下內容新增至您的選項物件

// Boolean - whether or not the chart should be responsive and resize when the browser does.
responsive: true,
// Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
maintainAspectRatio: false,
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!