【问题标题】:Why SVG mask doesn't work with CSS clip-path?为什么 SVG 蒙版不适用于 CSS 剪辑路径?
【发布时间】:2020-07-01 16:16:47
【问题描述】:

我想在图像上方创建一个 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>

【问题讨论】:

    标签: css svg


    【解决方案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>

    【讨论】:

    • 非常感谢!有效!从您的代码中学到很多东西!
    猜你喜欢
    • 1970-01-01
    • 2013-05-10
    • 2020-08-21
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2016-05-13
    • 2015-11-15
    相关资源
    最近更新 更多