繁体   English   中英

在Chart.js中向圆环图表添加标签会显示每个图表中的所有值

[英]Adding a label to a doughnut chart in Chart.js shows all values in each chart

我正在使用Chart.js在我的网站上绘制一系列图表,并且我编写了一个帮助方法来轻松绘制不同的图表:

drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, midLabel) {
    var ctx = ctxElement;
    var data = {
        labels: ctxDataLabels,
        datasets: ctxDataSets
    };

    Chart.pluginService.register({
        beforeDraw: function(chart) {
            var width = chart.chart.width,
                height = chart.chart.height,
                ctx = chart.chart.ctx;

            ctx.restore();
            var fontSize = (height / 114).toFixed(2);
            ctx.font = fontSize + "em sans-serif";
            ctx.textBaseline = "middle";

            var text = midLabel,
                textX = Math.round((width - ctx.measureText(text).width) / 2),
                textY = height / 2;

            ctx.fillText(text, textX, textY);
            ctx.save();
        }
    });

    var chart = new Chart(ctx, {
        type: ctxType,
        data: data,
        options: {
            legend: {
                display: false
            },
            responsive: true
        }
    });
}

drawChart()方法的最后一个参数包含应该添加到图表中间的标签。 Chart.pluginService.register部分是绘制标签的代码。 问题是当我多次执行drawChart方法(在我的情况下是三次)并在方法执行中提供每个图表的标签时,所有三个标签在每个图表上都显示在彼此的顶部。 我需要在相应的图表中显示每个标签。 除标签外,所有其他参数均已正确处理。

我如何实现这一目标?

一个简单的解决方法是在函数中添加另一个参数,以区分图表。

我之所以选择使用图表的id,那么你确定不会影响另一个。

首先需要编辑一下你的功能:

// !!
// Don't forget to change the prototype
// !!
function drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, midLabel, id) {
    var ctx = ctxElement;
    var data = {
        labels: ctxDataLabels,
        datasets: ctxDataSets
    };

    Chart.pluginService.register({
        afterDraw: function(chart) {
            // Makes sure you work on the wanted chart
            if (chart.id != id) return;

            // From here, it is the same as what you had

            var width = chart.chart.width,
                height = chart.chart.height,
                ctx = chart.chart.ctx;

            // ...
        }
    });

    // ...
}

从现在开始,当你调用你的函数时,不要忘记id:

// ids need to be 0, 1, 2, 3 ...
drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 1", 0);
drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 2", 1);
drawChart(ctxElement, ctxType, ctxDataLabels, ctxDataSets, "Canvas 3", 2);

您可以在这个小提琴上看到一个完整的工作示例(带有3个图表),这是一个预览:

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM