在SVG路径中居中文字 [英] Centering text in SVG path

查看:201
本文介绍了在SVG路径中居中文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在path中将text的水平和垂直居中与 startOffsettext-anchor属性,但是居中不起作用.

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>

推荐答案

为了获得所需的内容,我更改了路径的点.现在,路径从0,0开始.另外,我还删除了所有转换.如果您需要将路径设置在其他位置,则可以像在代码中一样在#tooltip上使用转换.

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.

请注意文本的属性dy ="35".这将使您的文字向上移动&在中心.

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>

这篇关于在SVG路径中居中文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆