我想将多个 SVG 元素内嵌在一个 SVG 中。
我有以下内容:
<svg>
<g>
<use width="28" height="28"class="cls-11"></use>
<text id="policyRectText" transform="translate(50,20)" class="cls-54">Runs on a small number of endpoints</text>
<circle r="15" stroke-width="4" transform="translate(250,15)" class="cls-8"></circle>
</g>
</svg>
因此,将元素定位在动态文本之前很容易,但如何定位在它之后呢?
最佳答案
我会这样做:
首先我将 <text>
在<g>
元素,因为它已转换,我需要获取边界框:
let bb = theTransformedText.getBBox();
一旦我有了文本的位置和大小 ( bb
),我就会使用数据来设置 cx
和 cy
圆的属性。
我已经注释掉了 <use>
元素,因为它没有 xlink:href
属性。
let bb = theTransformedText.getBBox();
let r = parseFloat(theCircle.getAttribute("r"));// the circle's radius.
let sw = parseFloat(theCircle.getAttribute("stroke-width"));// the stroke width
theCircle.setAttributeNS(null, "cx", bb.x + bb.width + r + sw/2);
// assuming that the font size is 16 you need to offset the circle half font size
theCircle.setAttributeNS(null, "cy", bb.y + 8);
<svg viewBox="0 -50 400 100">
<g>
<!--<use width="28" height="28"class="cls-11"></use>-->
<g id="theTransformedText">
<text id="policyRectText" transform="translate(50,20)" class="cls-54">Runs on a small number of endpoints</text>
</g>
<circle id="theCircle" r="15" stroke-width="4" class="cls-8"></circle>
</g>
</svg>
关于html - SVG - 文本后的内联位置元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54064026/