Show values on top of bars in chart.js

后端 未结 7 1127
自闭症患者
自闭症患者 2020-12-04 13:34

Please refer this Fiddle : https://jsfiddle.net/4mxhogmd/1/

I am working on chart.js If you see in fiddle, you will notice that value which is top on bar is not pro

7条回答
  •  遥遥无期
    2020-12-04 13:59

    Here is a more robust solution that will display the datapoint value inside the bar for cases where the axis height is close to the bar height. In other words, this will display the value above the bar and/or below the bar if the text will extend beyond the canvas visible area.

    Chart.plugins.register({
      afterDraw: function(chartInstance) {
        if (chartInstance.config.options.showDatapoints) {
          var helpers = Chart.helpers;
          var ctx = chartInstance.chart.ctx;
          var fontColor = helpers.getValueOrDefault(chartInstance.config.options.showDatapoints.fontColor, chartInstance.config.options.defaultFontColor);
    
          // render the value of the chart above the bar
          ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
          ctx.textAlign = 'center';
          ctx.textBaseline = 'bottom';
          ctx.fillStyle = fontColor;
    
          chartInstance.data.datasets.forEach(function (dataset) {
            for (var i = 0; i < dataset.data.length; i++) {
              var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
              var scaleMax = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._yScale.maxHeight;
              var yPos = (scaleMax - model.y) / scaleMax >= 0.93 ? model.y + 20 : model.y - 5;
              ctx.fillText(dataset.data[i], model.x, yPos);
            }
          });
        }
      }
    });
    

    You can enable your chart to use the plugin by adding the below property in your chart options.

    showDatapoints: true,
    

提交回复
热议问题