使用 viewBox 保持 <text> 元素在 <svg> 内部缩放

bgi*_*uga 1 html xml layout svg text

我试图将一些文本作为标签放入一些缩放元素内,但文本太大而无法放入容器中。我在这里能做什么?

<div class="t_container">
  <div class="t_x" style="position: relative;">
    <svg position="absolute" viewBox="0 0 6 1" preserveAspectRatio="none">
      <g>
        <rect x="0" y="0" width="1" height="0.4"><title>Nov-21</title></rect>
        <text x="0.5" y="0.5" fill="red">A<text>
      </g>
    <rect x="1" y="0" width="1" height="1"><title>Nov-22</title></rect>
    <rect x="2" y="0" width="1" height="1"><title>Nov-23</title></rect>       
    <rect x="3" y="0" width="1" height="1"><title>Nov-24</title></rect>
    <rect x="4" y="0" width="1" height="1"><title>Nov-25</title></rect>       
    <rect x="5" y="0" width="1" height="1"><title>Nov-26</title></rect></svg>
</div>
Run Code Online (Sandbox Code Playgroud)

这是一个带有结果的代码笔。

Ale*_*_TT 5

您的定制尺寸非常小viewport="0 0 6 1"。6px - 宽度,1px - 高度,所以这样的参数无法显示字体。

我将 viewBox 的大小增加了 100 倍viewBox="0 0 600 100"

为了清晰起见,正方形被涂上了不同的颜色。您可以根据您的选择更改它们的颜色。

文本放置在方块内。我希望这正是您使用该命令时想要的

<title> Nov-24 </ title>在正方形内。

但 SVG 中的命令<title>是一个系统工具提示,当您将光标悬停时,会显示其中的信息。工具提示的大小及其字体无法更改,因此我在方块中添加了更多标签<text> ... </ text>,您可以更改其参数。

<div class="t_container">
  <div class="t_x" style="position: relative;">
    <svg position="absolute"  viewBox="0 0 600 100" >
     <g>
        <rect x="0" y="0" width="100" height="40"><title>Nov-21</title></rect>
        <text x="35" y="75" font-size="36" fill="red">A</text>
      </g>
    <rect x="100" y="0" width="100" height="100" fill="orange">
	<title>Nov-22</title></rect> 
	  <text x="125" y="55" font-size="18" fill="white">Nov-22</text>

	  <rect x="200" y="0" width="100" height="100" fill="orangered">
	<title>Nov-23</title></rect>     
	 <text x="225" y="55" font-size="18" fill="white">Nov-23</text>
	 
	 
    <rect x="300" y="0" width="100" height="100" fill="green">
	<title>Nov-24</title></rect>
	 <text x="325" y="55" font-size="18" fill="white">Nov-24</text>
	 
    <rect x="400" y="0" width="100" height="100" fill="dodgerblue">
	<title>Nov-25</title></rect>     
    <text x="425" y="55" font-size="18" fill="white">Nov-25</text>
	
    <rect x="500" y="0" width="100" height="100" fill="yellowgreen">
	<title>Nov-26</title></rect> 
	<text x="525" y="55" font-size="18" fill="white">Nov-26</text>
	
	
	</svg>
</div>
Run Code Online (Sandbox Code Playgroud)