svg - 在路径中心显示文本 SVG
问题描述
我必须显示以 SVG 路径为中心的文本。这是 SVG 路径:
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="M 12.07137,236.59885 H 85.706728 V 262.5523 H 34.403405 v 59.75328 H 11.467802 Z"
id="no1"
inkscape:connector-curvature="0" />
<text
id="text6">
12.20%
</text>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 85.706728,236.59885 h 12.07137 v 51.30333 h 70.013942 v 12.67494 H 71.221083 v 48.88904 H 11.467802 V 322.30558 H 34.403405 V 262.5523 h 51.303323 z"
id="no2"
inkscape:connector-curvature="0" />
<text
id="text9">
12.20%
</text>
<path
style="fill:none;stroke:#000000;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
d="m 97.778098,236.59885 h 71.221082 l -1.20714,51.30333 H 97.778098 Z"
id="no3"
inkscape:connector-curvature="0" />
<text
id="text12">
12.20%
</text>
我得到了 js 代码,通过获取路径的 x,y 来显示文本,然后通过路径的 x,y 计算文本的 x,y(但它似乎不正确):
var paths = document.getElementsByTagName("path");
for (i = 0; i < paths.length; i++) {
var path = paths[i]; // path element
var text = path.nextElementSibling; // text element
if(text && text.nodeName === 'text') {
var new_x = document.createAttribute("x");
new_x.value = path.getBBox().width / 2 + path.getBBox().x - text.getBBox().width / 2;
text.setAttributeNode(new_x);
var new_y = document.createAttribute("y");
new_y.value = path.getBBox().y + path.getBBox().height / 2 + text.getBBox().height / 3;
text.setAttributeNode(new_y);
}
}
});
在附图中,红色区域似乎正确,但黄色区域和蓝色区域似乎不正确。那么任何人都可以帮助告诉我如何更正确地计算文本的 X、Y 值吗?
解决方案
推荐阅读
- javascript - 如何将媒体查询放入 javascript
- haskell - Haskell中Either和Except在用法上有什么区别?
- python - 格式化命令行字符串的代码约定是什么?
- r - 检查每组一个df是否至少有两个值与另一组匹配
- ios - Firebase 通知未在 iOS 上播放声音
- r - 导入 csv 并用闪亮的仪表板编写它们
- mysql - MySQL如何在没有过程/函数的情况下执行命令块
- javascript - 如何在 JS 上正确使用 devicemotion
- c# - MVC .NET 4.7.2 中的异步事务
- sql - 在 SQL 中收集具有最小权重的不同邻居