【发布时间】:2019-07-12 15:35:59
【问题描述】:
我想在 SVG 中将文本的上标和下标放在同一个位置。这是数学和化学方程式的要求。在 SVG 中似乎没有这样的要求。
要求是当上标和下标放在某些文本旁边时,它们的 x 值必须相同。这些上标和下标可能出现在文本之前或之后,并且该要求适用于这两种情况。首先,我尝试使用带有 x 和 y 坐标的 SVG 元素来放置它们,效果非常好(附件 1)。但是,当以编程方式查找每个元素的 x 和 y 坐标时,就会出现问题。
然后我尝试了 element with 并应用 dx,效果也很好,但 dx 随字体大小而变化。在我尝试实施自定义解决方案之前,我想知道是否有更好的解决方案。
我附上了我使用的代码和示例图像。
我的第一次尝试。
<?xml version="1.0" encoding="UTF-8"?>
<!-- Code that works well with x & y coordinates for all elements -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
viewBox="0 0 64 64" style="stroke-width:0;fill:black;font-size:24px;font-family:Sans-serif">
<text x="17" y="50" font-size="48px">B</text>
<text x="4" y="22">A</text>
<text x="43.59" y="22" font-size="36px">±</text>
<text x="4" y="63">Z</text>
<text x="43.59" y="63">C</text>
</svg>
第二次尝试 SVG 的推荐元素
<?xml version="1.0" encoding="UTF-8"?>
<!-- Textbook recommended for super and subscripts, unacceptable result -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
viewBox="0 0 128 128" style="stroke-width:0;fill:black;font-size:24px;font-family:Sans-serif">
<text x="1" y="64" font-size="24px" letter-spacing="-4">
<tspan baseline-shift="super" font-size="18px" >A</tspan>
<tspan baseline-shift="sub" font-size="18px" text-anchor="end">Z</tspan>
B
<tspan baseline-shift="super" font-size="18px" >±</tspan>
<tspan baseline-shift="sub" font-size="18px">C</tspan>
</text>
</svg>
第三次尝试对 tspan 元素使用负 dx。
<?xml version="1.0" encoding="UTF-8"?>
<!-- Code that works well with minus values for dx of subscripts -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
viewBox="0 0 128 128" style="stroke-width:0;fill:black;font-size:24px;font-family:Sans-serif">
<text x="1" y="64" font-size="24px" letter-spacing="-4">
<tspan baseline-shift="super" font-size="18px" >A</tspan>
<tspan baseline-shift="sub" dx="-10" font-size="18px" text-anchor="end">Z</tspan>
B
<tspan baseline-shift="super" font-size="18px" >±</tspan>
<tspan baseline-shift="sub" dx="-10" font-size="18px">C</tspan>
</text>
</svg>
没有错误消息。预期和实际结果显示在附加图像中。
1。所有 SVG 元素的 x 和 y 坐标结果
2.结果包含推荐的文本和 tspan 元素以及 super 和 sub 的基线偏移值
【问题讨论】:
-
听起来您使用了错误的技术,您应该改用 mathml。
-
这类似于我之前提出的一个问题,但这是一个纯 HTML 问题,因为这是一个 SVG 问题。 HTML 和 SVG 编码之间有一些相似之处,但这种情况下的结果会有所不同。
标签: svg text subscript superscript