How to Place Image on X-Axis

Asked

Viewed 184 times

3

I’m trying to put an image on this graph that represents the Labels, but how is a canvas I don’t know how to do this in Chartjs.

JS

Gráfico1

myBarChart = new Chart(chartBar, {
  type: 'bar',
  data: {
     labels: dataLabel,
     datasets: [{
        data: dataValue,
        backgroundColor: dataColor,
        borderColor: dataBColor,
        borderWidth: 1,
        label: "NPS"
     }]
  },
  options: {
     legendCallback: function(chart) {
         var text = [];
         text.push('<div class="col-xs-12 legendaBarChart no-padding">');
         for (var i = 0; i < dataLegend.length; i++) {
             text.push('<div class="col-xs-12 col-sm-12 no-padding">');
             text.push('<span>' + dataLegend[i] + '</span>');
             text.push('</div>');
         }
         text.push('</div>');
         return text.join("");
     },
     responsive: true,
     maintainAspectRatio: false,
     animation : {
        duration: 1000,
        easing: "linear",
        onComplete: function () {
           var chartInstance = this.chart,
           ctx               = chartInstance.ctx;
           ctx.font          = "15px 'Helvetica Neue', Helvetica, Arial, sans-serif";
           ctx.textAlign     = 'center';
           ctx.textBaseline  = 'bottom';
           ctx.fillStyle     = "#000000";

           this.data.datasets.forEach(function (dataset, i) {
              var meta = chartInstance.controller.getDatasetMeta(i);
              meta.data.forEach(function (bar, index) {
                 data = dataset.data[index];
                 ctx.fillText(data, bar._model.x, bar._model.y - 5);
              });
           });
        }  
     },
     legend: {
        display: false,
        position: 'top'
     },
     scales: {
        yAxes: [{
           ticks: {
              beginAtZero: true
           },
           stacked: true
        }]
     },
     title: {
        display: true,
        text: 'Gráfico Comparativo de',
        fontSize: 18
     },
     hover: {
        animationDuration: 0
     },
     tooltips: {
        enabled: false,
        mode: 'single',
        titleFontSize: 16,
        bodyFontSize: 15,
        titleSpacing: 0,
        bodySpacing: 5,
        callbacks : {
           title: function(tooltipItem, data){
              return 'NPS';
           },
           label: function(tooltipItem, data){
              return data.datasets[0].data[1];
           }
        }
     }
  }
});

On this property labels: dataLabel is where I mount an Array with the graph values, since it comes by Ajax. It does not accept HTML, so there is no way I can place an image.

In this part below, for example, I can find out the position of the bar and put the value just when it finishes being animated.

this.data.datasets.forEach(function (dataset, i) {
   var meta = chartInstance.controller.getDatasetMeta(i);
   meta.data.forEach(function (bar, index) {
      data = dataset.data[index];
      ctx.fillText(data, bar._model.x, bar._model.y - 5);
   });
});

1 answer

1


As at first I had not understood your question well, I am taking the opportunity to update my answer according to what we talked.

I never worked directly with Chartjs, but when consulting documentation for your bar chart template, I believe you will need a function similar to this:

onComplete: function () {
    var chartInstance = this.chart;
    var ctx = chartInstance.ctx;
    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) {
            imagemA = new Image();
            imagemA.src = 'img/imagem.png';
            imagemA.onload = function(){
            context.drawImage(imagemA, bar._model.x, height - ((height - bar._model.y) / 2));
        }),this)
    }),this);
}

OBS: I have not tested this solution, I believe it is with some errors and other information is missing. However, I hope it will help you to reach the final solution. Good luck!

  • 2

    But it is after the animation even that I have to do it. The problem is to add in the right place.

  • @Gumball Since there are no HTML elements for you to base on, I suspect you will have to adjust the positioning of the images with CSS rules applied to classes, dynamically. However as the number of columns / chart size may vary, this is impractical. Unfortunately I do not know what you could accomplish in this case.

  • @Gumball Try this link in English http://stackoverflow.com/questions/6011378/how-to-add-image-to-canvas you will need to use this function context.drawImage(<image>, posicaox, posicaoy); If it works I will modify my answer

  • So... I know how to do this. But I don’t know what the correct property is inside Chartjs' Canvas. Like, I can add a text inside the bar, but not in place of the label... I’m sure I’ll have to use that you sent me, but I don’t know where.

  • I get it, what you really need to figure out are the coordinates at which the image has to be printed. I would try to do this by calculating the percentage of height and width of the graph, but I believe the positions would not agree.

  • Please do so. I edited my question with the part of my code that shows how to find the bar position.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.