Skip to content Skip to sidebar Skip to footer

Add Background Text In Chartjs

I want to add an informational background text in the center of a ChartJS behind all chart drawings. Is there another way than using an image as shown here: How can i add an image

Solution 1:

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 belowthis.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)
  }
});

newChart(ctx, options);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script><body><canvasid="container"width="600"height="400"></canvas></body>

Solution 2:

Try this one

<div><spanclass='title'>TITLE GOES HERE</span><canvasid="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;
}

Post a Comment for "Add Background Text In Chartjs"