首页 > 解决方案 > 如何在 SVG 中跟踪开放路径的一个边缘

问题描述

我正在尝试制作一个允许用户在 SVG 图像中绘制线条的网页。绘图部分很好,但是每条线都需要携带一个填充线宽的标签(线宽15px)。

我尝试使用<textpath>引用他们绘制的线,但标签的基线最终会沿着线的中间向下延伸。这是一个屏幕截图,显示我的意思。

我尝试了各种方法来使用 CSS 和属性稍微推动文本,但我唯一的成功是使用 a transform,如果线条的方向突然转向,这通常会导致文本“溢出”。

我尝试过的另一个解决方案是生成第二条路径,该路径沿着用户绘制的路径的一个边缘运行,并将其用于<textpath>,但我正在努力寻找一种方法将用户绘制的路径点转换为对应的点到线的渲染边缘。

有谁知道使这些方法中的任何一种起作用的方法?

标签: svg

解决方案


我知道线条需要带有一个填充线条宽度的标签(线条为 15px 宽)。为了移动我使用的文本dy="4"

text{fill:white;stroke:none;font-family:consolas;}
path{stroke-width:15px;fill:none;}
<svg viewBox="50 150 350 150">
<defs>
<path id="path" d="M70,180Q100,330 195,225Q290,120 380,250"></path>
</defs>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#path" stroke="#000000"></use>

   <text stroke="#000000" font-size="12" dy="4">
      <textPath id="tp" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#path" startOffset="30%">
            just some words I wrote
      </textPath>
    </text>
  

</svg>

另一种选择是使用dominant-baseline="middle"

text{fill:white;stroke:none;font-family:consolas;}
path{stroke-width:15px;fill:none;}
<svg viewBox="50 150 350 150">
<defs>
<path id="path" d="M70,180Q100,330 195,225Q290,120 380,250" ></path>
</defs>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#path" stroke="#000000"></use>

   <text stroke="#000000" font-size="12" dominant-baseline="middle">
      <textPath id="tp" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#path" startOffset="30%">
            just some words I wrote
      </textPath>
    </text>
</svg>

我希望这是你问的。


推荐阅读