[Chartjs]-Chart.js 3.3.0 – Draw text on top of chart

6πŸ‘

βœ…

Best thing to do is write a custom plugin where you can put the text on the canvas, chart.js doesnt provide this functionallity out of the box

Example:

const customText = {
  id: 'customText',
  afterDraw: (chart, args, options) => {
    const {
      ctx,
      canvas
    } = chart;
    textObjects = options.text;

    if (textObjects.length === 0) {
      return;
    }

    textObjects.forEach((textObj) => {
      ctx.save();

      ctx.textAlign = textObj.textAlign || 'center';
      ctx.font = `${textObj.size || '20px'} ${textObj.font || 'Arial'}`;
      ctx.fillStyle = textObj.color || 'black'
      ctx.fillText(textObj.text, textObj.x, textObj.y)

      ctx.restore();
    })
  }
}

const 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: {
    plugins: {
      customText: {
        text: [{
            text: 'Lorem ipsum',
            x: 300,
            y: 150,
            textAlign: 'center',
            size: '30px',
            color: 'black',
            font: 'Arial black'
          },
          {
            text: 'Lorem ipsum2',
            x: 300,
            y: 250,
            textAlign: 'center',
            color: 'red',
            font: 'Arial black'
          }
        ]
      }
    }
  },
  plugins: [customText]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.0/chart.js"></script>
</body>

Leave a comment