javascript 可以将文本添加到 SVG 路径吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6999281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:38:41  来源:igfitidea点击:

Can text be added to an SVG path?

javascriptjquerysvg

提问by styler

Is it possible to add text to an svg path, I have created a svg triangle and would like to add a letter to the center of this but not sure if this is possible?

是否可以将文本添加到 svg 路径,我创建了一个 svg 三角形并想在其中心添加一个字母但不确定这是否可行?

回答by Phrogz

Yes. See section 10.13 of the SVG1.1 specification(titled "Text on a path") for information on using the textPathelement.

是的。有关使用该元素的信息,请参阅SVG1.1 规范的第 10.13 节(标题为“路径上的文本”)textPath

Summarized:

总结:

  1. Give your path an idattribute.
  2. Create <textPath xlink:href="#pathid">My text here</textPath>
  1. 给你的路径一个id属性。
  2. 创建 <textPath xlink:href="#pathid">My text here</textPath>

Here's an example straight from the spec:

这是直接来自规范的示例:

SVG Image with text following the curve of the path with ID "MyPath"

带有 ID 为“MyPath”的路径曲线的带有文本的 SVG 图像

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" 
  "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="12cm" height="3.6cm" viewBox="0 0 1000 300" version="1.1"
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <path id="MyPath"
          d="M 100 200 
             C 200 100 300   0 400 100
             C 500 200 600 300 700 200
             C 800 100 900 100 900 100" />
  </defs>
  <desc>Example toap01 - simple text on a path</desc>

  <use xlink:href="#MyPath" fill="none" stroke="red"  />
  <text font-family="Verdana" font-size="42.5" fill="blue" >
    <textPath xlink:href="#MyPath">
      We go up, then we go down, then up again
    </textPath>
  </text>

</svg>