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

如何实现文本裁剪动态变色网格的动画效果?

实现文本裁剪动态变色网格的方案

当然可以实现这个效果!你想要的是让动态变色网格只在文字轮廓内显示的文字遮罩效果,完全可以通过CSS的background-clip: text属性结合定位来搞定,下面是具体的实现步骤和调整后的代码:

核心思路

我们需要让动态网格层和文字层重叠,然后利用background-clip: text把网格裁剪成文字的形状,具体逻辑:

  • 将标题和网格容器放在同一个父容器中,通过绝对定位让两者完全重叠
  • 把标题文字设为透明,并用background-clip: text让网格只在文字区域显示
  • 确保网格容器的尺寸和标题完全匹配,铺满文字区域

完整代码实现

HTML(保留你的原有结构,无需大改)

<div id="title-pg"> 
  <h1 id="title">etch-a-sketch</h1> 
  <div id="title-grid-ctn"></div> 
</div>

CSS(关键样式调整)

#title-pg {
  position: relative;
  display: inline-block; /* 让容器随标题宽度自适应 */
}

#title {
  position: relative;
  z-index: 1; /* 确保文字层在网格层上方 */
  font-size: 5rem; /* 调大字体让效果更醒目 */
  font-weight: bold;
  color: transparent; /* 文字设为透明,露出下层网格 */
  background-clip: text;
  -webkit-background-clip: text; /* 兼容WebKit内核浏览器(如Safari) */
  margin: 0;
}

#title-grid-ctn {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  grid-template-columns: repeat(10, 1fr); /* 和你JS创建的10x10网格对应 */
  grid-template-rows: repeat(10, 1fr);
  gap: 1px; /* 可选:添加网格间隙,让格子更明显 */
  background: #fff; /* 可选:设置背景色,突出网格效果 */
}

.title-grid {
  margin: 0;
  padding: 0;
}

JavaScript(补充随机数函数,优化动画)

// 补充你用到的随机数生成函数
function rdmNumber() {
  return Math.floor(Math.random() * 256);
}

let titlePage = document.querySelector("#title-grid-ctn");
createTitleGrid();

function createTitleGrid() {
  for (let i = 0; i < Math.pow(10, 2); i++) {
    const titleGrid = document.createElement("div");
    titleGrid.classList.add("title-grid");
    titlePage.appendChild(titleGrid);
  }
}

const titleGrid = titlePage.querySelectorAll(".title-grid");
titleGrid.forEach((gridItem) => {
  gridItem.animate(
    [
      { backgroundColor: `rgb(${rdmNumber()}, ${rdmNumber()}, ${rdmNumber()})` },
      { backgroundColor: `rgb(${rdmNumber()}, ${rdmNumber()}, ${rdmNumber()})` },
    ],
    {
      duration: 2000,
      iterations: Infinity,
      delay: Math.random() * 1000, /* 可选:给每个格子添加随机延迟,动画更自然 */
      easing: "linear",
      direction: "alternate",
    }
  );
});

效果说明

  • 网格容器通过绝对定位完全覆盖在标题下方
  • background-clip: text会将下层的网格动画裁剪成标题文字的形状,透明的文字让网格只在文字轮廓内可见
  • 给每个格子添加随机延迟后,动画会更有层次感,不会显得过于同步

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 21:03:10