ChartJS 如何生成自定义图例?

ChartJS how to generate custom legend?

我在我的网站上使用 ChartJS v2.9.3,我有一个在长池中调用的函数,它从 API 中获取数据,我在其中生成图例以及来自 [=21] 的新数据=] 它可以改变。

我的旧代码是:

$('#legend-rc').html(chartRC.generateLegend());

现在我将我的 ChartJS 迁移到最新版本 3.7.0 但我得到 chartRC.generateLegend is not a function

通过查看文档,似乎 generateLegend() 已被删除,但我怎样才能像迁移后使用 v2 那样做一些事情?

因为我的数据集是动态加载的,所以我不得不在 afterDatasetUpdate

中添加图例逻辑

所以我的代码是这样的:

const chartRC = new Chart(document.getElementById("chartRC").getContext('2d'), {
    type: 'pie',
    data: {
        labels: [],
        datasets: [{
            fill: false,
            borderWidth: 2,
            pointBackgroundColor: '#0095ff',
            pointBorderColor: 'rgba(255,255,255,0)',
            pointHoverBackgroundColor: '#4683d3',
            data: [],
        }]
    },
    options: optionsRC,
    plugins: [{
        afterDatasetUpdate: function (chart, args, options) {
            if (chart.data.labels.length) {
                const chartId = chart.canvas.id
                const legendId = `${chartId}-legend`;
                const ul = document.createElement('ul');
                ul.setAttribute('data-chart-id', chart.id)
                chart.data.labels.forEach((label, i) => {
                    ul.innerHTML += `
                    <li>
                      <span style="background-color: ${chart.data.datasets[0].backgroundColor[i]}"></span>
                      ${label}
                    </li>
                `;
                })
                $(`#${legendId}`).delegate('li', 'click', legendClick);
                $(`#${legendId}`).delegate('li', 'mouseenter mouseleave', legendHover)
                return document.getElementById(legendId).appendChild(ul);
            }
            return;
        }
    }]
});