Create responsive SVG clip path / Making SVG <path> responsive

一笑奈何 提交于 2019-12-06 12:03:56

This answer distorts the shape of the clip path so that it always spans the whole image, regardless of its aspect ratio.

With clipPathUnits="objectBoundingBox", only coordinates between 0 and 1 will lie inside the bounding rectangle of your image. You have to scale down the path for that.

Fortunately, the viewBox for your path names its dimensions. Unfortunately, you cannot leave the computation of the scaling to the renderer, but must give a transformation directly: scale(1 / 810, 1 / 1012). See the restrictions for the content elements of a <clipPath>.

Both the SVG 1.1 and the SVG 2 spec name transform as a possible attribute of the <clipPath> itself, but neither define the coordinate system it should be applied in. For the sake of browser compatibility, it is probably better to leave that alone and use the transform on the <path> element, even if I can see that in Firefox there is no difference in the result.

.clipped-img {
    clip-path: url(#raindropClipPath);
    width: 100%;
    height: auto;
}

#raindropSVG {
    width: 0;
    height: 0;

}
<svg id="raindropSVG">
    <defs>
        <clipPath id="raindropClipPath" clipPathUnits="objectBoundingBox">
            <path transform="scale(0.0012345, 0.00098814)" d="M0,604.4C0,523.7,30.7,408.8,97.5,320,217,160.9,409.2,0,409.2,0S597.2,167.8,717,331c63,85.7,93,196.4,93,274,0,224.5-181.3,407-405,407S0,829.5,0,604.4Z"/>
        </clipPath>
    </defs>
</svg>

<img src="https://i.stack.imgur.com/zubYX.png" alt="" class="clipped-img">

SVG will always be responsive if only viewBox is specified.

Svg saves image proportions unless the value `preserveAspectRatio ="none" is specified.

Therefore, the path formativeclip-path will also be responsive.

A picture added to the SVG using the <image> tag will also be adaptive and maintain its proportions.

#raindropSVG {
    width: 75%;
    height: 75%;
}

.clipped-img {
clip-path: url(#raindropClipPath);
}
<svg id="raindropSVG" viewBox="0 0 800 800" preserveAspectRatio="xMinYMin meet">
    <defs>
        <clipPath id="raindropClipPath" >
            <path transform="scale(0.75)" d="M0,604.4C0,523.7,30.7,408.8,97.5,320,217,160.9,409.2,0,409.2,0S597.2,167.8,717,331c63,85.7,93,196.4,93,274,0,224.5-181.3,407-405,407S0,829.5,0,604.4Z"/>
        </clipPath>
    </defs>
<image class="clipped-img" xlink:href="https://i.stack.imgur.com/zubYX.png" x="0" y="0" width="800" height="800" />
	
	</svg>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!