JSFiddle - React, Tailwind, and code Playground

by denisstukalov

HTML

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<canvas id="profitPerTarget" height="500" style="padding: 10px"></canvas>

CSS

html, body {
  background-color: #121212;
}

JavaScript

function createDonatsChart(ctx, title, data, labels, middleText, type) {
  const originalData = [...data]
  const total = (originalData.map(el => el.profit).reduce((a, b) => a + b, 0))
  Chart.pluginService.register({
    beforeDraw: function(chart) {
      if (chart.config.options.elements.center) {
        // Get ctx from string
        const ctx = chart.chart.ctx;

        // Get options from the center object in options
        const centerConfig = chart.config.options.elements.center;
        const fontStyle = centerConfig.fontStyle || 'Asap';
        const txt = centerConfig.text;
        const color = centerConfig.color || '#000';
        const maxFontSize = centerConfig.maxFontSize || 75;
        const sidePadding = centerConfig.sidePadding || 20;
        const sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2)
        // Start with a base font of 30px
        ctx.font = `30px ${fontStyle}`;

        // Get the width of the string and also the width of the element minus 10 to give it 5px side padding
        const stringWidth = ctx.measureText(txt).width;
        const elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

        // Find out how much the font can grow in width.
        const widthRatio = elementWidth / stringWidth;
        const newFontSize = Math.floor(30 * widthRatio);
        const elementHeight = (chart.innerRadius * 2);

        // Pick a new font size so it will not be larger than the height of label.
        const fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);
        const minFontSize = centerConfig.minFontSize;
        const lineHeight = centerConfig.lineHeight || 25;
        const wrapText = false;

        if (minFontSize === undefined) {
          minFontSize = 20;
        }

        if (minFontSize && fontSizeToUse < minFontSize) {
          fontSizeToUse = minFontSize;
          wrapText = true;
        }

        // Set font settings to draw it correctly.
       ...