1

如何更改甜甜圈的文本大小react-chartjs-2

这个中心的文字太小了。

在此处输入图像描述

import React, {Fragment} from 'react';
import Chart from 'chart.js';
import {Doughnut} from 'react-chartjs-2';

const chartColor1 = "#de272c"
const chartColor2 = "#CED0D2"

// some of this code is a variation on https://jsfiddle.net/cmyker/u6rr5moq/
var originalDoughnutDraw = Chart.controllers.doughnut.prototype.draw;
Chart.helpers.extend(Chart.controllers.doughnut.prototype, {
  draw: function() {
    originalDoughnutDraw.apply(this, arguments);
    
    var chart = this.chart.chart;
    var ctx = chart.ctx;
    var width = chart.width;
    var height = chart.height;

    var fontSize = (height / 100).toFixed(2);
    ctx.font = fontSize + "px";
    ctx.fillStyle = chartColor1;
    ctx.textBaseline = "middle";

    var text = chart.config.data.text,
        textX = Math.round((width - ctx.measureText(text).width) / 2),
        textY = height / 2;

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

const DoughnutChart = (props) => {

  return (
    <Fragment>
      { props.aggregatedRating || props.rating
      ? 
      <div>
        <Doughnut
          data={{
            labels: [],
            datasets: [{
              data: [props.aggregatedRating, 100 - props.aggregatedRating],
              backgroundColor: [chartColor1, chartColor2],
              borderColor: [chartColor1],
              borderWidth: 0,
              weight: 1
              // hoverBackgroundColor: THEME_COLOR
            }],
            text: "24"
          }}
          options={{
            responsive: true,
            cutoutPercentage: 75,
            title:{
              display:false,
              // text:'Rating',
              // fontSize:200
            },
            legend:{
              display:false,
              // position:'right'
            },
          }}
          
        />
        </div>
      : <h4>No Rating</h4>
      }

    </Fragment>
  );
};

export default DoughnutChart;
4

1 回答 1

1

根据小提琴,您以像素为单位设置文本字体大小,为什么不尝试更改为em而不是px

...
var fontSize = (height / 100).toFixed(2);
ctx.font = fontSize + "em"; //<-------- here 
...
于 2021-01-20T10:22:46.740 回答