Chart JS 3上 Flink 的文本

mwkjh3gx  于 2023-05-22  发布在  Chart.js
关注(0)|答案(1)|浏览(176)

尝试在每个条形图的顶部绘制值。为什么每次鼠标悬停在不同的栏上时文本都在 Flink ?我该怎么做才能消除这个问题?
https://jsfiddle.net/wbpxemnh/

const ctx = document.getElementById('myChart');
  
  var myChart = new Chart(ctx, {
    data: {
      labels: ['21Q1','21Q2','21Q3','21Q4','22Q1','22Q2','22Q3','22Q4',],
      datasets: [
        {
            type: 'bar',
            label: 'Y Value',
            data: [2,3,4,4,5,7,5,4,],
            borderWidth: 1,
            backgroundColor: '#1E77E5',
        },
      ],
    },
    options: {
        responsive: true,
        animation: {
            onComplete: function ({chart}) {
                const ctx = chart.ctx;
                    ctx.textAlign = 'center';
                    ctx.fillStyle = "rgba(0, 0, 0, 1)";
                    ctx.textBaseline = 'bottom';
                    ctx.fillStyle = "#ffffff";
                    // Loop through each data in the datasets
                    this.data.datasets.forEach(function (dataset, i) {
                        var meta = chart.getDatasetMeta(i);
                        if(meta.hidden == null)
                        {   
                                meta.data.forEach(function (bar, index) {
                                var data = dataset.data[index];
                                ctx.fillText(data, bar.x, bar.y - 5);

                            });
                        }
                    });
                }
            },
    }
  });
t3psigkw

t3psigkw1#

这是因为它仅在动画完成后运行。要实现你想要的,你需要使用一个自定义插件。

const ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {
  data: {
    labels: ['21Q1', '21Q2', '21Q3', '21Q4', '22Q1', '22Q2', '22Q3', '22Q4', ],
    datasets: [{
      type: 'bar',
      label: 'Y Value',
      data: [2, 3, 4, 4, 5, 7, 5, 4, ],
      borderWidth: 1,
      backgroundColor: '#1E77E5',
    }, ],
  },
  options: {
    responsive: true,
    animation: {},
  },
  plugins: [{
    id: 'labels',
    afterDraw: (chart, args, opts) => {
      const ctx = chart.ctx;
      ctx.textAlign = 'center';
      ctx.fillStyle = "rgba(0, 0, 0, 1)";
      ctx.textBaseline = 'bottom';
      ctx.fillStyle = "#ffffff";
      // Loop through each data in the datasets
      chart.data.datasets.forEach(function(dataset, i) {
        var meta = chart.getDatasetMeta(i);
        if (meta.hidden == null) {
          meta.data.forEach(function(bar, index) {
            var data = dataset.data[index];
            ctx.fillText(data, bar.x, bar.y - 5);

          });
        }
      });
    }
  }]
});
canvas { background-color : black;
}
body {
  background-color:Black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
<body>
    <canvas id="myChart" width="600" height="400"></canvas>
</body>

已经有一个定制的插件,您可以用途:https://chartjs-plugin-datalabels.netlify.app/

相关问题