[Chartjs]-How to add images to chart labels with vue-chartjs?

2πŸ‘

βœ…

In the mounted of your vue component you can call the addPlugin (has to be done before the renderChart method) like this:

this.addPlugin({
  id: 'image-label',
  afterDraw: (chart) => {      
      var ctx = chart.chart.ctx; 
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      xAxis.ticks.forEach((value, index) => {  
        var x = xAxis.getPixelForTick(index);      
        var image = new Image();
        image.src = images[index],
        ctx.drawImage(image, x - 12, yAxis.bottom + 10);
      });      
    }
})

Documentation: https://vue-chartjs.org/api/#addplugin

1πŸ‘

It works in ChartJS version 4.0.1. data needs to return β€˜plugins’:

data() {
    return {
        plugins: [{
            afterDraw: chart => {
                    const ctx = chart.ctx;
                    const xAxis = chart.scales['x'];
                    const yAxis = chart.scales['y'];
                    xAxis.ticks.forEach((value, index) => {
                        let x = xAxis.getPixelForTick(index);
                        ctx.drawImage(images[index], x - 12, yAxis.bottom + 10)
                    });
                }
        }],
        data: {...

Please note that ctx should be chart.ctx and NOT chart.chart.ctx.. Similarly, it should be chart.scales[β€˜x’] and NOT chart.scales[β€˜x-axis-0’].

After you return plugins, this needs to be referenced in your Bar component like so..

<Bar :data="data" :options="options" :plugins="plugins"/>

Leave a comment