【问题标题】:Vertically align text inside of the svg circle垂直对齐 svg 圆圈内的文本
【发布时间】:2016-05-31 02:09:22
【问题描述】:

我正在尝试将 <text> 置于 <path> 元素的中心。路径是使用@opsb 很好的答案绘制的圆圈。我可以使用text-anchor='middle' 将文本水平居中。

有没有办法垂直居中?

<svg width="200px" height="200px" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <path id='path' fill="transparent" stroke='red' stroke-width='6'/>
  <text x="100" y="100" font-family="Verdana" font-size="50" fill="blue" text-anchor='middle'>5</text>
</svg>

JSFiddle 与 javascript。

【问题讨论】:

标签: javascript svg


【解决方案1】:

您需要使用对齐基线使文本垂直居中。

类似这样的:

&lt;text x="100" y="100" font-family="Verdana" font-size="50" fill="blue" text-anchor='middle' alignment-baseline="central"&gt;5&lt;/text&gt;

【讨论】:

    【解决方案2】:

    Svg 中心文本

    因为 svg 是响应式的 我通常输入一个大约是圆的半径的硬值。

    所以只需添加: transform="translate(0, 15)

    function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
      var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
    
      return {
        x: centerX + (radius * Math.cos(angleInRadians)),
        y: centerY + (radius * Math.sin(angleInRadians))
      };
    }
    
    function describeArc(x, y, radius, startAngle, endAngle) {
    
      var start = polarToCartesian(x, y, radius, endAngle);
      var end = polarToCartesian(x, y, radius, startAngle);
    
      var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";
    
      var d = [
        "M", start.x, start.y,
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y
      ].join(" ");
    
      return d;
    }
    
    $('#path').attr("d", describeArc(100, 100, 50, 0, 180));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <svg width="200px" height="200px" version="1.1" xmlns="http://www.w3.org/2000/svg">
      <path id='path' fill="transparent" stroke='red' stroke-width='6' />
      <text x="100" y="100" transform="translate(0, 15)" font-family="Verdana" font-size="50" fill="blue" text-anchor='middle'>5</text>
      <circle cx="100" cy="100" fill="black" r="2" />
      <circle cx="100" cy="50" fill="black" r="2" />
    </svg>

    【讨论】:

      【解决方案3】:

      您现在可以使用dominant-baseline="central" 来垂直对齐文本,而无需使用 javascript。

      <svg width="150px" height="150px" version="1.1" xmlns="http://www.w3.org/2000/svg">
        <circle cx="75" cy="75" r="69" stroke="red" fill="none" stroke-width="6" />
        <text x="75" y="75" font-family="Verdana" font-size="50" fill="blue" text-anchor='middle' dominant-baseline="central">5</text>
      </svg>

      Source

      【讨论】:

        猜你喜欢
        • 2020-09-26
        • 1970-01-01
        • 2018-11-06
        • 1970-01-01
        • 2013-08-08
        • 2016-07-01
        • 1970-01-01
        • 2012-01-15
        • 2015-11-22
        相关资源
        最近更新 更多