[Chartjs]-Add background text in ChartJS

3👍

You can extend the Chart‘s draw() function to add text to the chart. You can then control the positioning of the text by either calculating the x and y values for the middle of the chart, or specifying them, depending on how your chart is rendered:

let myLineExtend = Chart.controllers.line.prototype.draw;
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    myLineExtend.apply(this, arguments);
    // text styles below
    this.chart.chart.ctx.textAlign = "center"
    this.chart.chart.ctx.font = "20px Arial black";
    this.chart.chart.ctx.fillText("Lorem Ipsum Blah Blah", 300, 150)  // text, x-pos, y-pos
  }
});

Here’s a snippet demonstrating this:

let myLineExtend = Chart.controllers.line.prototype.draw;

let 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: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}

let ctx = document.getElementById('container').getContext('2d');
Chart.helpers.extend(Chart.controllers.line.prototype, {
  draw: function() {
    myLineExtend.apply(this, arguments);
    this.chart.chart.ctx.textAlign = "center"
    this.chart.chart.ctx.font = "20px Arial black";
    this.chart.chart.ctx.fillText("Lorem Ipsum Blah Blah", 300, 150)
  }
});

new Chart(ctx, options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script>

<body>
  <canvas id="container" width="600" height="400"></canvas>
</body>

1👍

Try this one

<div>
   <span class='title'>TITLE GOES HERE</span>
   <canvas id="bar" width="390" height="225"></canvas>
</div>


CSS : 
canvas {    
  display:inline;
}
.title {
    font-size: 47px;
    font-weight: bold;
    opacity: 0.2;
    z-index: -1;
    margin-top: 20px;
    position: absolute;
}

Leave a comment