SVG挖空文字

Avatar of Geoff Graham
Geoff Graham

这里的想法是想象三层叠加在一起,其中顶层用于在第二层中切出一个形状以显示第三层。

如果上面图表顶层上的文字是我们从第二层中切出的形状,那么下图说明了挖空文字的概念。

SVG 代码片段

这是一个代码片段,它设置了底层 (.knockout) ,挖空文字将显示在其中,中间层 (.knockout-text-bg) ,我们将从中切出,以及顶层 (.knockout-text) ,其中包含充当遮罩以切出第二层的 SVG 文本。

<div class="knockout">
  
  <svg class="knockout-text-container" width="100%" height="100%">
    
    <rect class="knockout-text-bg" width="100%" height="100%" fill="#000" x="0" y="0" fill-opacity="1" mask="url(#knockout-text)" />
    
    <mask id="knockout-text">
      <rect width="100%" height="100%" fill="#fff" x="0" y="0" />
      <text x="50%" y="50%" fill="#000" text-anchor="middle">Knock Out Text</text>
    </mask>
    
  </svg>
  
</div>

在本例中,<text> 坐标是完全任意的,可以根据添加文本的实际大小和位置进行调整。

请注意,第二层的 fill 为黑色,顶层的 fill 为白色。这就是遮罩的工作原理:白色与黑色形成完美的对比,并将隐藏黑色部分。我们可以使顶层完全不同的颜色,它不会完全隐藏黑色,但会允许一些黑色透过。

CSS 样式

其余的是 CSS 样式。例如,我们可以向底层添加背景渐变并设置字体大小以获得更戏剧性的效果。

.knockout {
  /* Ensure the bottom layer is full screen */
  height: 100vh;
  width: 100%;
  /* Add a colorful texture and cutom font-styling */
  background-image: linear-gradient(to left, #ff4e50 , #f9d423);
  text-transform: uppercase;
}

/* Knockout text font sizing for each line */

text:nth-child(2) {
  font-size: 5em;
}

text:nth-child(3) {
  font-size: 5.1em;
}

text:nth-child(4) {
  font-size: 15em;
}

查看 CodePen 上 Geoff Graham (@geoffgraham) 的笔:SVG挖空文字