[Chartjs]-How to point a Chart.js plugin to different doughnut charts?

4👍

Try below code. Tested and working. Hope it helps 🙂

   var doughnutCenterText = {
    beforeDraw: function (chart) {
    var width = chart.chart.width,
    height = chart.chart.height,
    ctx = chart.chart.ctx;

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

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

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

//Chart1
    this.doughnutChart1 = new Chart(this.doughnutCanvas1.nativeElement, {
        type: 'doughnut',
        data: {
            datasets: [{
                data: [65, 35],
                backgroundColor: [
                    'rgba(229, 57, 53, 1)',
                    'rgba(229, 57, 53, 0.2)',
                ],
                hoverBackgroundColor: [
                    'rgba(229, 57, 53, 1)',
                    'rgba(229, 57, 53, 0.2)',
                ],
                hoverBorderColor: [
                    '#fff',
                    '#fff'
                ]
            }]
        },
        plugins: [doughnutCenterText]    //Note here
    });

//Chart 2
    this.doughnutChart2 = new Chart(this.doughnutCanvas2.nativeElement, {
        type: 'doughnut',
        data: {
            datasets: [{
                data: [55, 45],
                backgroundColor: [
                    'rgba(0, 137, 123, 1)',
                    'rgba(0, 137, 123, 0.2)',
                ],
                hoverBackgroundColor: [
                    'rgba(0, 137, 123, 1)',
                    'rgba(0, 137, 123, 0.2)',
                ],
                hoverBorderColor: [
                    '#fff',
                    '#fff'
                ]
            }]
        },
        plugins: [doughnutCenterText]    //Note here
    });

Leave a comment