我是使用 HTML5 绘制 SVG 的新手。
我想做的是用 g element 在 SVG 中制作一组元素这样 g 元素内的所有元素都可以像一个组一样工作,并且可以从 < strong>上 g 元素.
所以,我所做的是这样的——
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<g x="1000" y="1000">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<text style="text-anchor: middle;" class="small">My Text</text>
</g>
</svg>
我期望 g 元素内的所有元素都将得到 x="1000"
和 y="1000"
所以我期望的输出是这样的-
但是我明白了-
重新-
我不喜欢在 text
元素中设置 x 和 y 元素。如果需要,我只想将相对的 x 和 y 设置到 text
元素中,但这应该是相对于 g 元素的。
任何人都可以帮助我在 SVG 中实现我的目标吗?
最佳答案
<g>
元素不支持 x 或 y 属性。不过,您可以改用转换。
我已将值从 1000 减少到 100,否则输出将超出外部 <svg>
的 500 x 300 Canvas 。元素。
我在文本元素上提供了额外的 x 和 y 属性,因此它的位置与您的示例中的一样。如果需要,您可以将文本本身放在 <g>
中。元素或 <svg>
元素。
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(100, 100)">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<text x="100" y="30" style="text-anchor: middle;" class="small">My Text</text>
</g>
</svg>
或使用额外的 <g>
元素以避免文本本身出现 x 和 y。
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(100, 100)">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<g transform="translate(100, 30)">
<text style="text-anchor: middle;" class="small">My Text</text>
</g>
</g>
</svg>
或者,您可以使用内部 <svg>
元素而不是 <g>
元素,因为它支持 x 和 y 属性
<svg width="500" height="300" xmlns="http://www.w3.org/2000/svg">
<svg x="100" y="100">
<title>SVG Title Demo example</title>
<rect width="200" height="50"
style="fill:wheat; stroke:blue; stroke-width:1px"/>
<text x="100" y="30" style="text-anchor: middle;" class="small">My Text</text>
</svg>
</svg>
关于javascript - 为 SVG 的 g 元素设置 X 和 Y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50596319/