如何使用文档内SVG为Div添加遮罩并适配可变尺寸?
问题:SVG遮罩覆盖可变尺寸容器并保持宽高比居中
我需要实现:用遮罩覆盖**尺寸可变(后续可能更改)**的容器Div,同时让SVG保持宽高比并居中于容器。预期效果为红色边框的黑色盒子中居中显示白色圆形,且后续要给circle元素添加动画,因此不适合使用CSS结合内联SVG的方案。
原代码
<div style=" border: 2px solid red; height: 200px; width: 300px; "> <div style=" height: 100%; width: 100%; background-color: black; mask: url(#curtain) center center / cover no-repeat; " > <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"> <defs> <mask id="curtain"> <rect fill="white" x="0" y="0" width="100" height="100" /> <circle fill="black" cx="50" cy="50" r="20" /> </mask> </defs> </svg> </div> </div>
原方案存在问题:无法覆盖父Div且遮罩未居中。
我参考了MDN文档中关于mask-size的说明,但不知如何应用:
If the mask-size is contain or cover:
The image is rendered by preserving its intrinsic proportion at the largest size contained within or covering the mask positioning area. If the image has no intrinsic proportion, then it is rendered at the size of the mask positioning area.
更新后的代码(仍有问题)
更新后已解决宽度问题,但height:100%仍无法填满容器高度,代码如下:
<div style="border: 2px solid red; height: 200px; width: 300px"> <div style="height: 100%; width: 100%; background-color: black; mask: url(#curtain) center center / cover no-repeat" > <svg xmlns="http://www.w3.org/2000/svg"> <mask id="curtain" maskUnits="objectBoundingBox" maskContentUnits="userSpaceOnUse" x="0" y="0" width="1" height="1" > <rect x="0" y="0" width="100%" height="100%" fill="white" /> <circle cx="50%" cy="50%" r="25" fill="black" /> </mask> </svg> </div> </div>
内容的提问来源于stack exchange,提问作者FieryRMS
相关产品推荐
相关产品推荐

