Complete Implementation of Dynamic Center Text in Chart.js Doughnut Charts

Nov 21, 2025 · Programming · 9 views · 7.8

Keywords: Chart.js | Doughnut Chart | Center Text | Plugin Development | Dynamic Font | Data Visualization

Abstract: This article comprehensively explores multiple approaches for adding center text in Chart.js doughnut charts, focusing on dynamic text rendering solutions based on the plugin system. Through in-depth analysis of the beforeDraw hook function execution mechanism, it elaborates on key technical aspects including text size adaptation, multi-line text wrapping, and dynamic font calculation. The article provides concrete code examples demonstrating how to achieve responsive text layout that ensures perfect centering in doughnut charts of various sizes.

Technical Background of Center Text Rendering in Doughnut Charts

In data visualization applications, doughnut charts are widely used due to their intuitive representation of proportions. However, Chart.js does not natively support adding text content directly in the center area of doughnut charts, which limits the expressiveness of the charts. By adding text labels in the center of doughnut charts, the readability and information density can be significantly enhanced, such as displaying overall percentages, key metrics, or chart theme descriptions.

Core Implementation Principle Analysis

Chart.js provides a powerful plugin system that allows developers to inject custom logic at different stages of chart rendering. For adding center text, the most effective approach is utilizing the beforeDraw hook function, which executes before the main chart elements are drawn, providing an ideal timing for text rendering.

The core of implementation lies in accurately calculating the rendering position and size of the text:

Chart.pluginService.register({
  beforeDraw: function(chart) {
    var ctx = chart.chart.ctx;
    var centerConfig = chart.config.options.elements.center;
    
    // Get the inner radius of the doughnut chart
    var innerRadius = chart.innerRadius;
    
    // Calculate center point coordinates
    var centerX = (chart.chartArea.left + chart.chartArea.right) / 2;
    var centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2;
    
    // Set text alignment
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    // Render text
    ctx.fillText(centerConfig.text, centerX, centerY);
  }
});

Dynamic Font Size Calculation Algorithm

To ensure text displays properly in doughnut charts of different sizes, dynamic font size calculation needs to be implemented. The algorithm is based on the following key parameters:

// Base font size
var baseFontSize = 30;

// Measure text width
var stringWidth = ctx.measureText(txt).width;

// Calculate available width (considering padding)
var sidePaddingCalculated = (sidePadding / 100) * (chart.innerRadius * 2);
var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

// Calculate width ratio and adjust font size
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(baseFontSize * widthRatio);

// Apply font size constraints
var fontSizeToUse = Math.min(newFontSize, elementHeight, maxFontSize);

Multi-line Text Wrapping Mechanism

When text content is too long or font size reaches the minimum value, text wrapping functionality needs to be enabled:

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

if (wrapText) {
  var words = txt.split(' ');
  var line = '';
  var lines = [];
  
  // Split words and calculate line width
  for (var n = 0; n < words.length; n++) {
    var testLine = line + words[n] + ' ';
    var metrics = ctx.measureText(testLine);
    var testWidth = metrics.width;
    
    if (testWidth > elementWidth && n > 0) {
      lines.push(line);
      line = words[n] + ' ';
    } else {
      line = testLine;
    }
  }
  
  // Adjust vertical position to center multi-line text
  centerY -= (lines.length / 2) * lineHeight;
  
  // Render text line by line
  for (var n = 0; n < lines.length; n++) {
    ctx.fillText(lines[n], centerX, centerY);
    centerY += lineHeight;
  }
  ctx.fillText(line, centerX, centerY);
}

Complete Configuration Options Detailed Explanation

This solution provides rich configuration options supporting high customization:

options: {
  elements: {
    center: {
      text: 'Custom Text Content',      // Text to display
      color: '#FF6384',                // Text color
      fontStyle: 'Arial',              // Font style
      sidePadding: 20,                 // Side padding percentage
      minFontSize: 20,                 // Minimum font size
      maxFontSize: 75,                 // Maximum font size
      lineHeight: 25                   // Line height (for multi-line text)
    }
  }
}

Responsive Layout Adaptation Strategy

To ensure proper display on different screen sizes and devices, responsive layout needs to be implemented:

// Dynamically calculate font size based on chart height
var fontSize = (chart.chart.height / 114).toFixed(2);
ctx.font = fontSize + "em sans-serif";

// Horizontal centering calculation
textX = Math.round((chart.chart.width - ctx.measureText(text).width) / 2);

// Vertical centering
textY = chart.chart.height / 2;

Performance Optimization and Best Practices

In practical applications, the following performance optimization points should be noted:

1. Avoid frequent text measurement: ctx.measureText() is a relatively expensive operation and should only be called when necessary.

2. Set reasonable font size ranges: Limit font size variation range through minFontSize and maxFontSize to avoid display issues in extreme cases.

3. Memory management: Properly use ctx.save() and ctx.restore() in plugins to manage drawing state.

Comparative Analysis with Other Solutions

Compared to solutions that directly modify Chart.js core code, plugin-based implementation offers better maintainability and compatibility. Plugins can extend chart capabilities without breaking existing functionality and are easily reusable across different projects.

Compared to simple static text solutions, dynamic calculation solutions can adapt to various complex display scenarios, including:

Practical Application Scenario Examples

This technology can be widely applied in:

Through proper configuration and extension, this solution can meet the display requirements for center text in most doughnut charts, providing richer and more professional presentation effects for data visualization applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.