3

我正在尝试在 Char JS 3.3.2 上使用自定义插入符号和位置构建条形图。

我刚刚在插件中添加了 beforeDraw 回调,但它从未被调用过。

plugins: {
  beforeDraw: () => {
    console.log('before Draw!!!!');
  },
  legend: {
    display: false
  },
  tooltip: {
    intersect: false,
    position: 'myCustomPosition',
    xAlign: 'center',
    yAlign: 'bottom',
    callbacks: {
      label: function(context) {
        var label = 'value : '

        if (context.parsed.y !== null) {
          label += context.parsed.y;
        }
        return label;
      },
      title: function() {
        return null;
      }
    }
  }
}

任何人都可以帮助我得到这个问题的答案吗?

我的代码在这里-> https://codepen.io/wsjraphael/pen/NWpZOjL

4

1 回答 1

3

您必须创建一个内联插件,如此处所述:https ://www.chartjs.org/docs/master/developers/plugins.html

您所做的是在选项部分中为所有不起作用的插件添加回调。

作为插件的 beforeDraw 回调示例:

const ctx = document.getElementById('myChart').getContext('2d');
const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      customPlugin: {
        consoleText: 'testText'
      }
    }
  },
  plugins: [{
    id: 'customPlugin',
    beforeDraw: (chart, args, options) => {
      let text = options.consoleText || 'fillerConsoleText';
      console.log(text)
    }
  }]
}

const chart = new Chart(ctx, options);
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>

于 2021-06-29T10:46:16.377 回答