You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS实现原图裁剪区域可见、其余区域覆盖灰色遮罩效果

实现思路

你当前的半透遮罩层.bg-image是全屏覆盖在原图上方的,所以即便选区盒子设了透明背景,也会被上层的半透遮罩挡住。我们可以通过修改遮罩层的样式,把选区对应位置挖空,就能实现选区透明、其余区域半透灰的效果。

方案1:使用CSS mask属性实现(推荐,代码简洁)

直接给半透遮罩层加mask属性,在对应选区位置挖空,不需要改动HTML结构:

.bounded-image {
  width: fit-content;
  position: relative;
}
img {
  width: 292px;
}
.bordered-image {
  position: absolute;
  border: 1px dashed #5035e1;
  box-sizing: border-box;
  width: 140.816px;
  height: 260.12px;
  top: 71.2428px;
  left: 76.4561px;
  background: transparent;
  z-index: 5; /* 保证边框显示在遮罩上层 */
}
.bg-image {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 4;
  background: black;
  opacity: 0.4;
  /* 核心:挖空选区位置 */
  -webkit-mask: linear-gradient(#000, #000) padding-box, linear-gradient(#000, #000);
  -webkit-mask-size: 100% 100%;
  -webkit-mask-position: 0 0;
  -webkit-mask-composite: xor;
  mask-composite: exclude;
  -webkit-mask-origin: content-box;
  mask-origin: content-box;
  padding: 71.2428px calc(100% - 76.4561px - 140.816px) calc(100% - 71.2428px - 260.12px) 76.4561px;
}

HTML结构不需要改动。

方案2:四边拼接实现(兼容性最好,兼容旧浏览器)

不用修改特殊CSS属性,直接把遮罩层拆成上下左右四个半透块,中间空出选区位置即可。

/* 删掉原来的.bg-image样式,替换为下面四个区域的样式 */
.mask-top {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 71.2428px;
  background: rgba(0,0,0,0.4);
  z-index: 4;
}
.mask-bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: calc(100% - 71.2428px - 260.12px);
  background: rgba(0,0,0,0.4);
  z-index: 4;
}
.mask-left {
  position: absolute;
  top: 71.2428px;
  left: 0;
  width: 76.4561px;
  height: 260.12px;
  background: rgba(0,0,0,0.4);
  z-index: 4;
}
.mask-right {
  position: absolute;
  top: 71.2428px;
  right: 0;
  width: calc(100% - 76.4561px - 140.816px);
  height: 260.12px;
  background: rgba(0,0,0,0.4);
  z-index: 4;
}

HTML调整为:

<div class="bounded-image">
  <img src="https://qoiowqcb.app.blr.streamoid.com/mls-data/streamoid_internal/images/76da8ac2445d14d23529390b63b19d4a"/>
  <div class="mask-top"></div>
  <div class="mask-right"></div>
  <div class="mask-bottom"></div>
  <div class="mask-left"></div>
  <div class="bordered-image" ></div>
</div>

两种方案都可以实现预期效果,方案1代码更简洁,方案2兼容性更好,可以根据实际场景选择。

内容的提问来源于stack exchange,提问作者goldy priyadarshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 18:45:04