如何为图表js使用内联插件内部标题?

问题描述

我正在创建一个包含两个甜甜圈图的JavaScript网页。创建一个图表,我正在使用一个函数,并为每个图表使用不同的数据调用两次。但是,当我这样做时,甜甜圈图中间的文本不仅针对当前图表被更改为两个图表。我该如何分别为每个文本写文字? 这是我的代码

function chart(dummynames,dummyValues,dummyColors,percentage,id) {
  //dummy names,dummy values and dummy colors are arrays

  new Chart(document.getElementById(id),{
    type: 'doughnut',data: {
      labels: dummynames,datasets: [{
        label: "tessers",backgroundColor: dummyColors,data: dummyValues,}]
    },options: {
      title: {
        display: true,align: 'center',horizontalAlign: "center",verticalAlign: "bottom",dockInsidePlotArea: true
      },legend: {
        display: false
      },cutoutPercentage: 70,},});

  Chart.pluginService.register({
    beforeDraw: function(chart) {
      var width = chart.chart.width,height = chart.chart.height + 35,ctx = chart.chart.ctx;

      ctx.restore();
      var fontSize = (height / 200).toFixed(2);
      ctx.font = fontSize + "em sans-serif";
      ctx.textBaseline = "middle";

      var text = percentage,textx = Math.round((width - ctx.measureText(text).width) / 2),textY = height / 2;

      ctx.fillText(text,textx,textY);
      ctx.save();
    }
  })
}

enter image description here

解决方法

您应该将Chart.pluginService.register放在chart函数之外,以确保仅被调用一次。

请查看修改后的代码,并查看其工作原理。

Chart.pluginService.register({
  beforeDraw: function(chart) {
    var width = chart.chart.width,height = chart.chart.height + 35,ctx = chart.chart.ctx;

    ctx.save();
    var fontSize = (height / 200).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "middle";

    var text = chart.data.datasets[0].percentage,textX = Math.round((width - ctx.measureText(text).width) / 2),textY = height / 2;

    ctx.fillText(text,textX,textY);
    ctx.restore();
  }
});

function chart(dummynames,dummyValues,dummyColors,percentage,id) {
  new Chart(document.getElementById(id),{
    type: 'doughnut',data: {
      labels: dummynames,datasets: [{
        label: "tessers",backgroundColor: dummyColors,data: dummyValues,percentage: percentage
      }]
    },options: {
      title: {
        display: true,align: 'center',horizontalAlign: "center",verticalAlign: "bottom",dockInsidePlotArea: true
      },legend: {
        display: false
      },cutoutPercentage: 70,},});
}

chart(['A','B'],[5,6],['red','blue'],'26.846%','myChart1');
chart(['X','Y'],[7,5],['green','purple'],'19.451%','myChart2');
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<div style="display: flex">
  <div>
    <canvas id="myChart1"></canvas>
  </div>
  <div>
    <canvas id="myChart2"></canvas>
  </div>
</div>

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...