Text inside the bar via chart.js - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Text inside the bar via chart.js

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.bundle.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//www  . j a  v a2s  . c  om
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Green"],
    datasets: [{
      label: '# of Votes',
      data: [12, 23]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero:true
        }
      }]
    },
    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) - 10);
          }),this)
        }),this);
      }
    }
  }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myChart" width="400" height="400"></canvas>  
   </body>
</html>

Related Tutorials