在图表JS v3上添加beforeDraw回调



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

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

最新更新