我不确定这是否是最好的方法。我正在尝试制作一个 SVG,其中包含可缩放部分和固定部分。它看起来像这样:
当网页加载时,我不知道容器的高度是多少,但我知道宽度。我希望连接线根据高度进行缩放,但保持带有加号的框居中,如下所示:
我已经尝试过 x1、y1 等的线路设置,但我无法找到一种方法来做到这一点而不诉诸 javascript。SVG 不是最好的选择吗?这是我到目前为止所拥有的:
<svg class="s2">
<line x1="50%" y1="0" x2="50%" y2="10%" style="stroke:rgba(255,0,0,.9);stroke-width:1px;"></line> <!-- top joining line -->
<g id="square" x="50%" y="50%" width="16px" height="16px">
<line x1="5" y1="8" x2="11" y2="8" style="stroke:rgba(255,0,0,.9);stroke-width:1px;"></line> <!-- plus horizontal line -->
<line x1="8" y1="5" x2="8" y2="11" style="stroke:rgba(255,0,0,.9);stroke-width:1px;"></line> <!-- plus vertical line -->
<rect x="4" y="4" width="8" height="8" style="fill:transparent;stroke:rgba(0,0,0,.5);"></rect>
</g>
<line x1="50%" y1="90%" x2="50%" y2="100%" style="stroke:rgba(255,0,0,.9);stroke-width:1px;"></line> <!-- bottom joining line -->
<line x1="90%" y1="50%" x2="100%" y2="50%" style="stroke:rgba(255,0,0,.9);stroke-width:1px;"></line> <!-- right joining line -->
</svg>
Run Code Online (Sandbox Code Playgroud)
javascript 是我唯一的选择吗?我尝试使用类似的值
calc(50% - 5px)
Run Code Online (Sandbox Code Playgroud)
用于线路定位,但似乎不支持。如果是这样就可以解决问题。
对于解决方案,您必须结合两种技术:
首先将矩形定位在坐标原点的中心,并给出以像素为单位的大小。首先简单地从-50% 到+50% 不间断地绘制连接线。然后中央矩形后面的部分被遮盖掉,尺寸再次以像素为单位。
最后,所有内容都被移动transform:translate(50%, 50&)以填充 SVG。需要注意的是,CSS 变换属性可以有单位,而SVG 变换表示属性只能有无单位数字。因此必须将其写入style属性(或样式表)中。
#outermost {
transform:translate(50%, 50%);
}
g line {
stroke:rgba(255,0,0,.9);
stroke-width:1px;
}
g rect {
fill:none;
stroke:rgba(0,0,0,.5);
}Run Code Online (Sandbox Code Playgroud)
<svg xmlns="http://www.w3.org/2000/svg" class="s2" width="24" height="100">
<mask id="cp">
<rect x="-50%" y="-50%" width="100%" height="100%" fill="white"></rect>
<rect x="-6" y="-6" width="12" height="12" fill="black"></rect>
</mask>
<g id="outermost">
<g mask="url(#cp)">
<line x1="0" y1="-50%" x2="0" y2="50%"></line>
<line x1="0" y1="0" x2="50%" y2="0"></line>
</g>
<line x1="-3" y1="0" x2="3" y2="0"></line>
<line x1="0" y1="-3" x2="0" y2="3"></line>
<rect x="-4" y="-4" width="8" height="8"></rect>
</g>
</svg>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10611 次 |
| 最近记录: |