寻找能让我轻松管理 svg 矩形/圆形区域中动态注入(inject)的文本(长度未知)的解决方案。
目前,设计师通过使用 AI 和其他设计软件为我生成 svg。 在生成的代码中,文本元素的位置由坐标决定,这意味着每次文本长度变化都会迫使开发人员手动更改坐标以保持适当的对齐。
是否有一种通用的方法可以独立于文本的长度并始终将其正确对齐在中间(水平和垂直)?
下面的代码示例及其可视化。
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 1106.3 443" style="enable-background:new 0 0 1106.3 443;" xml:space="preserve">
<style>
.rect-header { fill: #AAA; }
.rect-bg { fill: #CCC; }
</style>
<rect class="rect-header" width="1106.3" height="39.9"/>
<rect y="39.7" class="rect-bg" width="553.2" height="32.7"/>
<rect y="72.4" class="rect-bg" width="553.2" height="32.7"/>
<rect x="553.2" y="39.7" class="rect-bg" width="553.2" height="32.7"/>
<rect x="553.2" y="72.4" class="rect-bg" width="553.2" height="32.7"/>
<text transform="matrix(1 0 0 1 525.1992 25.7028)">HEADER</text>
<text transform="matrix(1 0 0 1 235.1992 60.7028)">48.1</text>
<text transform="matrix(1 0 0 1 815.0431 60.7029)">103</text>
<text transform="matrix(1 0 0 1 810.2572 93.731)">ABC</text>
<text transform="matrix(1 0 0 1 229.0706 93.7309)">DEFG</text>
</svg>
最佳答案
使用 text-anchor="middle"
指定文本应以您提供的坐标为中心,而不是从那里开始。
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" viewBox="0 0 1106.3 443">
<style>
.rect-header { fill: #AAA; }
.rect-bg { fill: #CCC; }
</style>
<rect class="rect-header" width="1106.3" height="39.9"/>
<rect y="39.7" class="rect-bg" width="553.2" height="32.7"/>
<rect y="72.4" class="rect-bg" width="553.2" height="32.7"/>
<rect x="553.2" y="39.7" class="rect-bg" width="553.2" height="32.7"/>
<rect x="553.2" y="72.4" class="rect-bg" width="553.2" height="32.7"/>
<g text-anchor="middle">
<text x="553.2" y="25.7">HEADER</text>
<text x="276.6" y="60.7">48.1</text>
<text x="829.8" y="60.7">103</text>
<text x="829.8" y="93.7">ABC</text>
<text x="276.6" y="93.7">DEFGHIJKLMNOPQRSTUVWXYZ</text>
</g>
</svg>
关于javascript - SVG - 在 svg 元素/ block 中居中动态文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45521822/