Matt
Matt

Reputation: 8962

Centering text in SVG path

I am trying to center horizontally and vertically text in path with the startOffset and text-anchor attributes, but centering doesn't work.

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
<svg id="line-vis" width="640" height="300" viewBox="0 0 640 300" preserveAspectRatio="none" style="cursor: pointer; overflow: visible; position: relative;">
   <g>
      <g class="line" pointer-events="none" transform="translate(365.1979064941406,134.5977783203125)">
         <path id="tooltip-line-vis" d="M120 60 L120 0 L0 0 L0 60 L54 60 L60 66 66 60" fill="#FFFFFF" stroke="#D2DBE9" transform="translate(-60,-75)" style="opacity: 1;"></path>
         <text text-anchor="middle" style="opacity: 1;">
            <textPath class="yLabelVal" xlink:href="#tooltip-line-vis" startOffset="50%" style="opacity: 1;font-size: 16px;font-weight: 500;line-height: 20px;fill: rgb(8, 40, 101);">$5,104.90</textPath>
         </text>
      </g>
      <rect width="640" height="300" fill="none" pointer-events="all"></rect>
   </g>
</svg>

Upvotes: 1

Views: 1275

Answers (1)

enxaneta
enxaneta

Reputation: 33062

In order to get what you need I've changed the points of the path. Now the path begins at 0,0. Also I've removed all the transforms. If you need your path in a different position you may use transforms on #tooltip as I did in my code.

Please note the attribute dy="35" for the text. This is moving your text upward & in the center.

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
<svg id="line-vis" width="640" height="300" viewBox="0 0 640 300" preserveAspectRatio="none" style="cursor: pointer; overflow: visible; position: relative;">
   <g id="tooltip" transform="translate(50,10)">
      <g class="line" pointer-events="none" >
         <!--<path id="tooltip-line-vis" d="M0,60 L54,60 60,66 66,60 120,60 120,0 0,0 0,60"  stroke="#D2DBE9" style="opacity: 1;"></path>-->
        
        <path id="tooltip-line-vis" d="M0,0 L120,0 120,60 66,60 60,66 54,60 0,60 0,0"  stroke="#D2DBE9" style="opacity: 1;"></path>

         <text text-anchor="middle" style="opacity: 1;" fill="gold" dy="35">
            <textPath class="yLabelVal" xlink:href="#tooltip-line-vis" startOffset="60" >$5,104.90</textPath>
         </text>
      </g>
      <rect width="640" height="300" fill="none" pointer-events="all"></rect>
   </g>
</svg>

Upvotes: 3

Related Questions