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

如何在SVG上挖透明矩形孔 使所有穿过孔洞的path区域透明

SVG全局挖透明孔洞实现方案

实现该需求不需要给每个path单独设置属性,只需要对所有path统一分组加遮罩即可,步骤如下:

  • 先在SVG内部定义<mask>遮罩:遮罩内先绘制覆盖整个SVG视口的白色矩形(白色对应内容正常显示),再绘制你需要的孔洞形状,填充为纯黑色(黑色对应内容透明)
  • 将所有动画path都包裹在同一个<g>分组标签内,给这个分组添加mask属性关联提前定义好的遮罩,即可实现所有path统一挖洞的效果
  • 如果需要调整孔洞的形状、位置、大小,只需要修改遮罩内黑色图形的参数即可,支持矩形、圆形、自定义path等任意形状

下面是基于你提供的代码修改后的完整示例:

CSS代码

path {
  transform-origin: 50% 0%;
}
@keyframes path0 {
  0% {
    transform: rotate(-10deg);
  }
  100% {
    transform: rotate(10deg);
  }
}
@keyframes path1 {
  0% {
    transform: rotate(-30deg);
  }
  100% {
    transform: rotate(30deg);
  }
}
@keyframes path2 {
  0% {
    transform: rotate(40deg);
  }
  100% {
    transform: rotate(-40deg);
  }
}
.background--custom {
  height: 100%;
  width: 100%;
  /* 如果需要孔洞透出SVG下方的页面内容,删除下面的background-color属性即可 */
  background-color: red;
}

SVG代码

<svg class="background--custom" id="demo" viewBox="0 0 100 100" preserveAspectRatio="none">
  <defs>
    <!-- 定义挖洞遮罩 -->
    <mask id="holeMask">
      <!-- 全白区域:对应内容正常显示 -->
      <rect x="0" y="0" width="100" height="100" fill="white" />
      <!-- 黑色区域:对应位置挖透明洞,可自定义大小位置形状 -->
      <rect x="25" y="25" width="50" height="50" fill="black" />
    </mask>
  </defs>
  <!-- 所有path放入分组,统一应用遮罩 -->
  <g mask="url(#holeMask)">
    <path fill="#D6D6D6" fill-opacity="1" d="M-100 -100L200 -100L200 50L-100 50Z" style="animation: path0 5s linear infinite alternate;" />
    <path fill="#DEFFFF" fill-opacity="1" d="M-100 -100L200 -100L200 50L-100 50Z" style="animation: path1 5s linear infinite alternate;" />
    <path fill="#DAFFF5" fill-opacity="1" d="M-100 -100L200 -100L200 20L-100 20Z" style="animation: path2 5s linear infinite alternate;" />
  </g>
</svg>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:36:05