【问题标题】:Add beforeDraw callback on chart JS v3在图表 JS v3 上添加 beforeDraw 回调
【发布时间】:2021-09-11 12:24:59
【问题描述】:

我正在尝试在 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

【问题讨论】:

    标签: chart.js chart.js3


    【解决方案1】:

    您必须创建一个内联插件,如此处所述: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>

    【讨论】:

    • 非常感谢!!终于可以回电了!!
    猜你喜欢
    • 1970-01-01
    • 2023-02-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多