gpt4 book ai didi

svg - 使用纯 SVG 将内联标签添加到水平条

转载 作者:行者123 更新时间:2023-12-04 08:35:48 29 4
gpt4 key购买 nike

我使用下面的 SVG 代码构建了一个水平条形图。没关系,但我还需要图表前后两个内联标签。我知道如何用 HTML 和 CSS 添加它们,但我只想用纯 SVG 来解决这个问题。如何做到这一点?

  <svg class="chart" width="300px" height="40">
<g transform="translate(0,0)">
<rect width="82%" height="22" fill="lightskyblue"></rect>
<rect width="100%" height="22" style="fill:none; stroke-width:1; stroke:gray;"></rect>
<text y="30" dx="0.25em" dy=".35em">0</text>
<text x="20%" y="10" dy=".35em" fill="red">|</text>
<text x="20%" y="30" dx="-0.25em" dy=".35em" fill="red">13</text>
<text x="100%" y="30" dx="-1.25em" dy=".35em">63</text>
</g>
</svg>

这是我现在拥有的:

enter image description here

这就是我想要的:

enter image description here

最佳答案

为了使其正常工作,我将您的代码用作更大 svg 元素中的嵌套 svg。请注意我使用的是 viewBox 属性,其中 x 分量具有负值 (-50),为文本留出空间。

svg{border:solid;}
<svg class="chart" width="300px" viewBox="-50 0 400 40">
<text y="20" x="-45">TXT</text>
<text x="345" y="20" text-anchor="end">TXT</text>
<svg viewBox="0 0 300 40" width="300">
<rect width="82%" height="22" fill="lightskyblue"></rect>
<rect width="100%" height="22" style="fill:none; stroke-width:1; stroke:gray;"></rect>
<text y="30" dx="0.25em" dy=".35em">0</text>
<text x="20%" y="10" dy=".35em" fill="red">|</text>
<text x="20%" y="30" dx="-0.25em" dy=".35em" fill="red">13</text>
<text x="100%" y="30" dx="-1.25em" dy=".35em">63</text>
</svg>
</svg>

我必须告诉你,我不会为矩形的位置和大小设置百分比。我会使用用户单位(没有单位标识符)来完成它,我不需要将它包装在另一个 svg 元素中。

更新

OP 正在评论

Can you give another example, without percentages for the position and size of the rects and without wrapping it in another svg element

svg{border:solid}
<svg class="chart" width="300px" viewBox="-50 0 400 40">
<text y="20" x="-45">TXT</text>
<text x="345" y="20" text-anchor="end">TXT</text>

<rect width="246" height="22" fill="lightskyblue"></rect>
<rect width="300" height="22" style="fill:none; stroke-width:1; stroke:gray;"></rect>
<text y="30" dx="0.25em" dy=".35em">0</text>
<text x="60" y="10" dy=".35em" fill="red">|</text>
<text x="60" y="30" dx="-0.25em" dy=".35em" fill="red">13</text>
<text x="300" y="30" dx="-1.25em" dy=".35em">63</text>
<svg>

关于svg - 使用纯 SVG 将内联标签添加到水平条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64809288/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com