svg - 使用纯 SVG 将内联标签添加到水平条
问题描述
我使用波纹管 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>
这就是我现在所拥有的:
这就是我想要的:
解决方案
为了使它工作,我将您的代码用作更大的 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正在评论
你能再举一个例子吗,没有矩形的位置和大小的百分比,也没有将它包装在另一个 svg 元素中
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>
推荐阅读
- spresense - 带数字麦克风的 Sony Spresense Arduino 录音
- python-3.x - 如何在python中调用帮助函数以确定返回什么?
- java - 如何使用 Applescript 和 Java 在 iTunes 中播放歌曲预览?
- python - 使用 execv & ptrace 在 linux 中执行 selenium-webdriver python 程序
- java - 如何修复布尔方法中的死代码警告?(i++)
- javascript - 下载大图像的小版本 - 客户端 - 没有后端功能 - javascript
- python - 遍历python的数据框
- android - 如何在 Flutter 中读取音频扩展并在 ListView 中显示?
- encoding - 英特尔 QuickSync 错误:打开输出流 #0:0 的编码器时出错 - 可能是不正确的参数,例如 bit_rate、rate、width 或 height
- ios - 如何在领域中保存多个对象,为每个项目创建不同的行