How to add a text centered on my donut-chart?

Viewed 160

In my react-app I want to add a title to my donut chart in chart.js.

import { Doughnut } from "react-chartjs-2";
import "../styles/DonutChart.css";
import {Chart as ChartJS, ArcElement, Tooltip, Legend, Chart} from 'chart.js';

ChartJS.register(ArcElement, Tooltip, Legend);

type DonutProps = {
    values: number[]
    names: string[]
}

export default function DonutChart({values, names}: DonutProps) {

    const hoverLabel = {
        id: 'hoverLabel',
        afterDraw(chart: Chart) {
            const {ctx, chartArea: {width, height}} = chart;
            ctx.save();

            ctx.font = "bolder 50px Arial";
            ctx.fillStyle = "blue";
            ctx.textAlign = "center";
            ctx.fillText("Test", width / 2, height / 2)
        }
    };

    const data = {
        labels: names,
        datasets: [
            {
                data: values,
                backgroundColor: [
                    '#707B52',
                    '#BDC4A7',
                    '#8E6E53',
                    '#615A5B',
                    '#92B4A7',
                    '#93B5C6',
                    '#518AA7',
                    '#B56B45',
                ],
                hoverBackgroundColor: [
                    "#FF6283",
                ],
            }
        ],
        plugins: [hoverLabel]
    }

    const options = {
        cutout: "70%",
    }

    return (
        <div id={"donutchart"}>
            <Doughnut data={data} options={options}/>
        </div>
    )
}

My npm-dependency:

"react-chartjs-2": "^4.1.0",

How to make the text visible?

0 Answers
Related