纯CSS在图片上实现向导指引!!(遮罩镂空效果)

871 阅读2分钟

方式一: 使用mask-image的id选择器

解析:多个镂空添加多个rect标签即可,通过改变url中的选择器

  • mask-image:属性第一个参数url中使用id选择要镂空的mask,后面linear-gradient(red, red)随意但是要加上
  • rect标签:属性x: 镂空区域左边间距;y: 上边距;rx、ry:圆角值
  • 优点:方便,代码简单,灵活修改镂空定位、大小、圆角;浏览器放大缩小镂空定位也不会偏离
  • 缺点:谷歌浏览器118以下版本不支持
<div class="content">
  <img src="./test.png" />
  <div class="mask">
    <svg width="100%" height="100%">
       <mask id="rounded-mask">
          <rect x="200px" y="175px" width="299px" height="346px" rx="14px" ry="14px" fill="white" />
       </mask>
       <mask id="rounded-mask-array">
         <rect x="200px" y="175px" width="299px" height="346px" rx="14px" ry="14px" fill="white" />
         <rect x="946px" y="175px" width="514px" height="346px" rx="6px" ry="6px" fill="white" />
       </mask>
    </svg>
  </div>
</div>
.content {
    width: 1500px;
    position: relative;
    margin: auto;
}
img {
    width: 100%;
}
.mask {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    mask-image: url(#rounded-mask-array), linear-gradient(red, red);
    mask-repeat: no-repeat; /* 设置遮罩图像是否重复 */
    mask-composite: exclude;
    background: rgba(194, 193, 193, 0.6);
    z-index: 99;
}

效果:

dbb0cac661a24bf1b0cc8b26660307e5.png

方式二:绘制svg路径,使用path

解析:通过改变path标签的d属性来绘制不同的镂空形状

  • 优点:浏览器兼容性好
  • 缺点:很难绘制多个镂空区域,有可以挖出两矩形且圆角的大佬,可以分享一下
  • 1920是可以修改灰色区域宽度;911是高度;a-h中的10是圆角值
<svg width="100%" height="100%">
    <path d="`M 1920 0 L 0 0 L 0 911 L 1920 911 L 1920 0 Z M ${left} ${top} h 0 a 10 10 0 0 1 10 10 v ${height} a 10 10 0 0 1 -10 10 h -${width} a 10 10 0 0 1 -10 -10 v -${height} a 10 10 0 0 1 10 -10 Z`" style="fill: rgba(0, 0, 0, 0.5); pointer-events: auto; cursor: auto;"></path>
</svg>

效果:

6b739707a7e0457a993285f46501a3fe.png

方式三:使用mask-image的图片地址

mask-image的url使用图片镂空,

  • 优点:兼容低版本浏览器;
  • 缺点:可设置定位大小,但需要与镂空区域一样的形状的图片,且只能镂空一个区域
<div class="content">
    <img src="./test.png" />
    <div class="mask"></div>
</div>
.content {
    width: 1500px;
    position: relative;
    margin: auto;
}
img {
    width: 100%;
}
.mask {
    position: absolute;
    background: rgba(194, 193, 193, 0.6);
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    z-index: 99;
    mask-image: url('./md-touch-icon.png'), linear-gradient(red, red);
    mask-repeat: no-repeat;
    mask-composite: exclude;
    -webkit-mask-image: url('./md-touch-icon.png'), linear-gradient(red, red);
    -webkit-mask-repeat: no-repeat;/* 设置遮罩图像是否重复 */  
    -webkit-mask-composite: destination-out;
    -webkit-mask-size: 100px 100px, cover; /* 设置遮罩图像的大小 */  
    -webkit-mask-position: 100px 100px, center center; /* 设置遮罩图像的定位 */  
}

效果:我这里用的图片是一个直角矩形

4e60c1c8bcde41d0a574f8a142824bea.png

以上是我个人经验总结,如有错误欢迎大佬们纠正鸭~