Nic*_*rie 5 javascript css svg
我想实现以下目标:
调整 svg 元素内图像的大小以完美适合多边形内部,而且它完全可见,并且不会被剪切(请参阅 jsfiddle)。
我已经解决了很多 stackoverflow 问题,但无法弄清楚:
代码:
<svg width="50%" height="50%" viewBox="0 0 25 10" preserveAspectRatio="none">
<defs>
<pattern id="im1" width="100%" height="100%" preserveAspectRatio="none">
<image preserveAspectRatio="none" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://dummyimage.com/600x400/abc" width="100%" height="100%"></image>
</pattern>
</defs>
<polygon points="0,10 29, 10 10, 0" x="0" y="0" style="fill:url(#im1);"></polygon>
</svg>Run Code Online (Sandbox Code Playgroud)
看https://jsfiddle.net/f8ktzyLw/
有人能指出我正确的方向吗?这只能通过 svg 实现还是需要 JavaScript/Canvas ?
多边形大小 29px 水平比 viewBox = "0 0 25 10" 大 4px
我添加了一个灰色框架来显示 SVG 画布的边界
<svg width="50%" height="50%" viewBox="0 0 25 10" preserveAspectRatio="none" style="border:1px solid gray">
<defs>
<pattern id="im1" width="100%" height="100%" preserveAspectRatio="none">
<image preserveAspectRatio="none" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://dummyimage.com/600x400/abc" width="100%" height="100%"></image>
</pattern>
</defs>
<polygon points="0,10 29, 10 10, 0" x="0" y="0" style="fill:url(#im1);"></polygon>
</svg>Run Code Online (Sandbox Code Playgroud)
为了使多边形完全适合SVG的画布,需要将SVG的水平尺寸增加4px viewBox="0 0 29 10"
<svg width="50%" height="50%" viewBox="0 0 29 10" preserveAspectRatio="none" style="border:1px solid gray">
<defs>
<pattern id="im1" width="100%" height="100%" preserveAspectRatio="none">
<image preserveAspectRatio="none" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://dummyimage.com/600x400/abc" width="100%" height="100%"></image>
</pattern>
</defs>
<polygon points="0,10 29, 10 10, 0" x="0" y="0" style="fill:url(#im1);"></polygon>
</svg>Run Code Online (Sandbox Code Playgroud)
或者您可以保持多边形的尺寸viewBox="0 0 25 10不变,但随后您需要将多边形的水平尺寸减小相同的值4px
<svg width="50%" height="50%" viewBox="0 0 25 10" preserveAspectRatio="none" style="border:1px solid gray">
<defs>
<pattern id="im1" width="100%" height="100%" preserveAspectRatio="none">
<image preserveAspectRatio="none" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://dummyimage.com/600x400/abc" width="100%" height="100%"></image>
</pattern>
</defs>
<polygon points="0,10 25, 10 10, 0" x="0" y="0" style="fill:url(#im1);"></polygon>
</svg>Run Code Online (Sandbox Code Playgroud)