我有一个 SVG 箭头,我想根据包装 DIV 的宽度改变它的长度(例如)。
我之前的所有尝试都导致了这种行为(缩放整个 SVG):
而不是这个,我想实现这个行为:
是否可以通过简单地向代码添加百分比值来改变 SVG 内部的单个形状?如果没有,我该如何执行此操作?
SVG 代码:
<svg width="35px" viewBox="0 0 35 985" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="Group" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(0.000000, 0.000000)">
<rect id="Rectangle-2" fill="#5FDCC7" x="12" y="19.7987928" width="11" height="100%"></rect>
<polygon id="Triangle" fill="#5FDBC6" points="17.5 0 35 20.7887324 0 20.7887324"></polygon>
<rect id="Rectangle-3" fill="#5FDBC6" x="0" y="973.110664" width="35" height="11"></rect>
</g>
</svg>
最佳答案
一般而言,无法创建部分无法缩放的可缩放 SVG。如果一个 SVG 有一个 viewBox,并且你缩放它,那么所有的内容都会缩放。无法将某些内容标记为不受缩放影响。
您可以获得的最接近的结果是将缩放限制在 X 轴上。然而,箭头仍会拉伸(stretch)。
<svg width="35px" height="150px" viewBox="0 0 35 985" preserveAspectRatio="none">
<g id="Group" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(0.000000, 0.000000)">
<rect id="Rectangle-2" fill="#5FDCC7" x="12" y="19.7987928" width="11" height="100%"></rect>
<polygon id="Triangle" fill="#5FDBC6" points="17.5 0 35 20.7887324 0 20.7887324"></polygon>
<rect id="Rectangle-3" fill="#5FDBC6" x="0" y="973.110664" width="35" height="11"></rect>
</g>
</svg>
<svg width="35px" height="300px" viewBox="0 0 35 985" preserveAspectRatio="none">
<g id="Group" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" transform="translate(0.000000, 0.000000)">
<rect id="Rectangle-2" fill="#5FDCC7" x="12" y="19.7987928" width="11" height="100%"></rect>
<polygon id="Triangle" fill="#5FDBC6" points="17.5 0 35 20.7887324 0 20.7887324"></polygon>
<rect id="Rectangle-3" fill="#5FDBC6" x="0" y="973.110664" width="35" height="11"></rect>
</g>
</svg>
如果您想要一个通用的解决方案,那么您必须监控调整大小事件并动态更新 SVG。
有限的偷偷摸摸的聪明解决方案......
综上所述,有一种巧妙的技术可以在有限的情况下发挥作用。限制是:
- SVG 仅在一个方向上拉伸(stretch)。
- “非缩放”部分位于拉伸(stretch)的任一端或两端
- 端部是实心的,没有任何孔。
- 您可以接受 SVG 的背景是纯色而不是透明的。
这是使用此技术实现的形状演示。如果您水平调整窗口大小,您会看到它适本地拉伸(stretch)。:
<svg width="100%" height="35px">
<svg viewBox="0 0 1 1" preserveAspectRatio="none">
<rect x="0" y="0" width="1" height="1" fill="white"/>
<rect x="0" y="0.4" width="1" height="0.2" fill="#5FDBC6"/>
</svg>
<svg viewBox="0 0 0.2 1" preserveAspectRatio="xMinYMid">
<rect x="0" y="0" width="0.2" height="1" fill="#5FDBC6"/>
</svg>
<svg viewBox="0 0 0.8 1" preserveAspectRatio="xMaxYMid">
<rect x="0" y="0" width="0.8" height="1" fill="white"/>
<polygon points="0,0 0.8,0.5 0,1" fill="#5FDBC6"/>
</svg>
</svg>
关于css - 动态调整单个形状的大小而不缩放整个 SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41258693/