我有一个带有 <path>
的 SVG嵌入到网站中的元素将用作图像 map 。客户告诉我她想要在每条路径上嵌入数字和文字,而在其他路径上嵌入文字。有什么想法可以实现吗?
也许如果我可以访问每个区域的中心坐标,我可以使用一些 JS 将文本定位到那里,但我不确定该怎么做。 以下是一些带有示例路径的代码,用于隐藏客户端信息:
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 916.32 2130.72" style="enable-background:new 0 0 916.32 2130.72;" xml:space="preserve">
<g id="Layer_2">
<image style="overflow:visible;" width="1909" height="4439" id="bg" xlink:href="map.jpg" transform="matrix(0.48 0 0 0.48 0.0681 -1.0503)">
</image>
</g>
<g id="Layer_1">
<a xlink:href="#">
<path id="path1" class="st0" d="M766.56,190.56l78.24-82.08l28.8,4.8l18.24,79.68l-26.88,72.48l-86.4-33.6l-0.48-7.2V213.6
l-1.92-7.68l-4.32-6.72L766.56,190.56z"></path>
</a>
<path id="path2" class="st0" d="M530.88,272.16l64.8-2.88l5.76,74.4l-67.68,1.44L530.88,272.16z"></path>
<path id="path3" class="st0" d="M407.52,276.96l45.12-0.48l5.28,72.48l-83.52,4.32L407.52,276.96z"></path>
</g>
</svg>
最佳答案
你可以使用 <textPath>
用于绘制所有文本的 SVG 元素。对于每个文本,您必须使用一个 <textPath>
和一个 <path>
它的元素。沿着 <path>
的形状呈现文本, 将文本括在 <textPath>
中具有 href
的元素引用 <path>
的属性元素。这一切<path>
您必须添加到 <defs>
中的元素具有独特元素 ID
.在上面的链接下阅读有关此元素及其属性的更多信息。
这很重要:你所有的<textPath>
您必须在 <text>
中编写的元素由于 zIndex
元素在您的 SVG 末尾(最新添加的元素在最上面)。
这是演示它是如何工作的:
<svg width="400" height="120" viewBox="0 0 1000 300">
<defs>
<path id="MyPath1"
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"/>
<path id="MyPath2" d="M300,300L700,50"/>
</defs>
<!-- red line under text. You can delete the following line -->
<use href="#MyPath1" fill="none" stroke="red"/>
<text font-family="Verdana" font-size="42.5">
<textPath href="#MyPath1">We go up, then we go down, then up again</textPath>
<textPath href="#MyPath2" fill="red">And the second text</textPath>
</text>
很遗憾,我们无法使用您的代码,因为它不完整。
关于javascript - 如何将文本放在 SVG 中的特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64670680/