在图表 JS v3 上添加 beforeDraw 回调

Sun*_*Won 5 chart.js chart.js3

我正在尝试在 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;
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Lee*_*lee 9

您必须创建一个内联插件,如下所示: 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);
Run Code Online (Sandbox Code Playgroud)
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
Run Code Online (Sandbox Code Playgroud)