首页 > 解决方案 > 在路径中心显示文本 SVG

问题描述

我必须显示以 SVG 路径为中心的文本。这是 SVG 路径:

     style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
     d="M 12.07137,236.59885 H 85.706728 V 262.5523 H 34.403405 v 59.75328 H 11.467802 Z"
     id="no1"
     inkscape:connector-curvature="0" />
  <text
     id="text6">
      12.20%
    </text>
  <path
     style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
     d="m 85.706728,236.59885 h 12.07137 v 51.30333 h 70.013942 v 12.67494 H 71.221083 v 48.88904 H 11.467802 V 322.30558 H 34.403405 V 262.5523 h 51.303323 z"
     id="no2"
     inkscape:connector-curvature="0" />
  <text
     id="text9">
      12.20%
    </text>
  <path
     style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
     d="m 97.778098,236.59885 h 71.221082 l -1.20714,51.30333 H 97.778098 Z"
     id="no3"
     inkscape:connector-curvature="0" />
  <text
     id="text12">
      12.20%
    </text>

我得到了 js 代码,通过获取路径的 x,y 来显示文本,然后通过路径的 x,y 计算文本的 x,y(但它似乎不正确):

  var paths = document.getElementsByTagName("path");
   for (i = 0; i < paths.length; i++) {
    var path = paths[i]; // path element
    var text = path.nextElementSibling; // text element
    if(text && text.nodeName === 'text') {
      var new_x = document.createAttribute("x"); 
      new_x.value = path.getBBox().width / 2 + path.getBBox().x - text.getBBox().width / 2; 
      text.setAttributeNode(new_x);

      var new_y = document.createAttribute("y");
      new_y.value = path.getBBox().y + path.getBBox().height / 2 + text.getBBox().height / 3;
      text.setAttributeNode(new_y);
    }
  }
});

在附图中,红色区域似乎正确,但黄色区域和蓝色区域似乎不正确。那么任何人都可以帮助告诉我如何更正确地计算文本的 X、Y 值吗? 在此处输入图像描述

标签: svgpath

解决方案


推荐阅读