首页 文章

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

提问于
浏览
5

我正在使用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方法(在我的情况下为三次)并在方法执行中提供每个图表的标签时,所有三个标签在每个图表上都显示在彼此的顶部 . 我需要在相应的图表中显示每个标签 . 除标签外,所有其他参数均已正确处理 .

我如何实现这一目标?

1 回答

  • 1

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

    我选择使用图表的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);
    

    你可以在this fiddle(有3个图表)上看到一个完整的工作示例,这是一个预览:

    enter image description here

相关问题