当前位置: 首页 > 知识库问答 >
问题:

如何使用图表在甜甜圈图表中添加文本。js?

王宏扬
2023-03-14

如何在甜甜圈图表中呈现文本,我正在使用ChartJs。

共有3个答案

宋子辰
2023-03-14

您必须修改代码,如:在图表中。Doughnut.defaults

labelFontFamily : "Arial",
labelFontStyle : "normal",
labelFontSize : 24,
labelFontColor : "#666"

然后在函数drawPieSegments

ctx.fill文本(数据[0]. value"%",宽/2-20,宽/2,200);

看到这个拉动:https://github.com/nnnick/Chart.js/pull/35

这是一把小提琴http://jsfiddle.net/mayankcpdixit/6xV78/实现同样的目标。

唐沈义
2023-03-14

这里是以上解决方案的清理和组合示例-响应(尝试调整窗口大小)、支持动画自动对齐、支持工具提示

https://jsfiddle.net/cmyker/u6rr5moq/

Chart.types.Doughnut.extend({
    name: "DoughnutTextInside",
    showTooltip: function() {
        this.chart.ctx.save();
        Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);
        this.chart.ctx.restore();
    },
    draw: function() {
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);

        var width = this.chart.width,
            height = this.chart.height;

        var fontSize = (height / 114).toFixed(2);
        this.chart.ctx.font = fontSize + "em Verdana";
        this.chart.ctx.textBaseline = "middle";

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

        this.chart.ctx.fillText(text, textX, textY);
    }
});

var data = [{
    value: 30,
    color: "#F7464A"
}, {
    value: 50,
    color: "#E2EAE9"
}, {
    value: 100,
    color: "#D4CCC5"
}, {
    value: 40,
    color: "#949FB1"
}, {
    value: 120,
    color: "#4D5360"
}];

var DoughnutTextInsideChart = new Chart($('#myChart')[0].getContext('2d')).DoughnutTextInside(data, {
    responsive: true
});
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js"></script>
<body>
    <canvas id="myChart"></canvas>
</body>
</html>
萧安怡
2023-03-14

其他答案都没有根据文本量和甜甜圈大小调整文本大小。这里有一个小脚本,你可以在中间动态地放置任何数量的文本,它会自动调整大小。

例子:http://jsfiddle.net/kdvuxbtj/

它将采取任何数量的文本在甜甜圈大小完美的甜甜圈。为了避免接触边缘,可以将侧边填充设置为圆内部直径的百分比。如果不设置它,它将默认为20。您还可以选择颜色、字体和文本。插件会处理其余部分。

插件代码将以30px的基本字体大小开始。从那里,它将检查文本的宽度,并将其与圆的半径进行比较,并根据圆/文本宽度比调整其大小。

它的默认最小字体大小为20px。如果文本超出最小字体大小的界限,它将换行文本。包装文本时的默认行高为25px,但您可以更改它。如果您将默认的最小字体大小设置为false,文本将变得无限小,并且不会换行。

它还有一个默认的最大字体大小为75px,以防没有足够的文本和字体太大。

这是插件代码

Chart.pluginService.register({
  beforeDraw: function(chart) {
    if (chart.config.options.elements.center) {
      // Get ctx from string
      var ctx = chart.chart.ctx;

      // Get options from the center object in options
      var centerConfig = chart.config.options.elements.center;
      var fontStyle = centerConfig.fontStyle || 'Arial';
      var txt = centerConfig.text;
      var color = centerConfig.color || '#000';
      var maxFontSize = centerConfig.maxFontSize || 75;
      var sidePadding = centerConfig.sidePadding || 20;
      var 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
      var stringWidth = ctx.measureText(txt).width;
      var elementWidth = (chart.innerRadius * 2) - sidePaddingCalculated;

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

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

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

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

      // Set font settings to draw it correctly.
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      var centerX = ((chart.chartArea.left + chart.chartArea.right) / 2);
      var centerY = ((chart.chartArea.top + chart.chartArea.bottom) / 2);
      ctx.font = fontSizeToUse + "px " + fontStyle;
      ctx.fillStyle = color;

      if (!wrapText) {
        ctx.fillText(txt, centerX, centerY);
        return;
      }

      var words = txt.split(' ');
      var line = '';
      var lines = [];

      // Break words up into multiple lines if necessary
      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;
        }
      }

      // Move the center up depending on line height and number of lines
      centerY -= (lines.length / 2) * lineHeight;

      for (var n = 0; n < lines.length; n++) {
        ctx.fillText(lines[n], centerX, centerY);
        centerY += lineHeight;
      }
      //Draw text in center
      ctx.fillText(line, centerX, centerY);
    }
  }
});

在图表对象中使用以下选项

options: {
  elements: {
    center: {
      text: 'Red is 2/3 the total numbers',
      color: '#FF6384', // Default is #000000
      fontStyle: 'Arial', // Default is Arial
      sidePadding: 20, // Default is 20 (as a percentage)
      minFontSize: 20, // Default is 20 (in px), set to false and text will not wrap.
      lineHeight: 25 // Default is 25 (in px), used for when text wraps
    }
  }
}

感谢@Jenna Sloan在此解决方案中使用的数学帮助。

 类似资料:
  • 问题内容: 我正在使用ChartJs如何在甜甜圈图表中呈现文本。 问题答案: 您必须修改以下代码: 然后在功能上

  • 我正在尝试用ApachePOI创建甜甜圈图,但没有任何信息或示例。我尝试使用饼图的例子,但没有成功。你能帮我解决这个问题吗?

  • 当使用图表时。js库,我可以添加多个甜甜圈在我的页面上没有问题。 http://www.chartjs.org/docs/#doughnut-饼图 但是我找不到一种方法总是显示工具提示——不仅仅是当鼠标悬停在甜甜圈上时。有人知道这是否可能吗?

  • 以下是基本饼图的示例。 我们已经在Highcharts Configuration Syntax一章中看到了用于绘制图表的配置 。 下面给出了基本饼图的示例。 配置 (Configurations) 现在让我们看一下所采取的其他配置/步骤。 系列 (series) 将系列类型配置为基于饼图。 series.type决定图表的系列类型。 这里,默认值是“line”。 使用innerSize将inne

  • 本文向大家介绍不带内部饼图的HTML Highcharts甜甜圈图示例,包括了不带内部饼图的HTML Highcharts甜甜圈图示例的使用技巧和注意事项,需要的朋友参考一下 将数据提供为包含两个元素的数组的数组。设置innerSize并获取甜甜圈样式。 参数将具有- 设置大小的代码片段-

  • 问题内容: 我的Ajax方法看起来像这样 我想显示一个类似这样的甜美“警告警告”弹出窗口 如果他们单击“取消”,则不应进行ajax调用;如果选择“是”,则仅应进行调用 所以任何人都可以告诉我如何将Ajax方法嵌入方法中 谢谢 问题答案: 举一个简单的例子,我可以向您展示我如何在自己的网站上进行操作。我将Ajax呼叫放入了甜蜜警报中。 因此,只有在您按下确认按钮时才能进行ajax调用。我希望这可以帮