为什么SVG蒙版不适用于CSS剪切路径?

时间:2020-07-01 07:04:59

标签: css svg

我想在图像上方创建一个svg蒙版,我的代码在下面,但是它不起作用,我不知道这是怎么回事。我想要做的实际效果是在所有部分上方加一个圆圈遮罩,然后向下滚动页面,图片将在圆圈内一一显示。

<div class="mask">
  <svg width="0" height="0">
    <defs>
        <clipPath id="circle-mask" clipPathUnits="objectBoundingBox">
            <circle cx="100" cy="100" r="40"/>
        </clipPath>
    </defs>
  </svg>    
</div>
<div class="section"><img src="https://images.unsplash.com/photo-1593532847202-e818146e134a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" /></div>
<div class="section"><img src="https://images.unsplash.com/photo-1593532847202-e818146e134a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" /></div>
 ....

<style>
.mask {position: absolute;top:0;left:0;width:100%;height: 100%;z-index:2;}
.section {width: 100%; height: 100vh;}
.section img {width: 100%; clip-path: url(#circle-mask);}
</style>

1 个答案:

答案 0 :(得分:1)

使用clipPathUnits="objectBoundingBox"时,您需要考虑[0,1]范围内的值,因此您必须像下面那样更正clip-path

.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
}

.section {
  height: 100vh;
  border:1px solid;
}

.section img {
  width:100%;
  height:100%;
  clip-path: url(#circle-mask);
}
<div class="mask">
  <svg width="0" height="0" >
    <defs>
        <clipPath id="circle-mask" clipPathUnits="objectBoundingBox">
            <circle cx="0.5" cy="0.5" r="0.4"/>
        </clipPath>
    </defs>
  </svg>
</div>
<div class="section"><img src="https://picsum.photos/id/1/400/400" ></div>
<div class="section"><img src="https://picsum.photos/id/1/400/400" style="width:auto;"></div>

使用CSS蒙版可以获得相同的效果:

.section {
  height: 100vh;
  border:1px solid;
}

.section img {
  height:100%;
  width:100%;
  -webkit-mask: radial-gradient(farthest-side,#fff 80%,transparent 81%);
          mask: radial-gradient(farthest-side,#fff 80%,transparent 81%);
}
<div class="section"><img src="https://picsum.photos/id/1/400/400" ></div>
<div class="section"><img src="https://picsum.photos/id/1/400/400" style="width:auto;"></div>