Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

show text in central of paths SVG

I have to display the text that centers in the SVG paths. Here is the SVG path:

     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>

I got js code to display text by get x, y of path then calculate the x,y of text by x,y of path(but it seems not correct):

  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);
    }
  }
});

In the attached image, the red zone seems correct, but the yellow zone and blue zone seems is not correct. So can anyone please help to tell me how to calculate the value X, Y of text more correctly? enter image description here

question from:https://stackoverflow.com/questions/65873331/show-text-in-central-of-paths-svg

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...