CSS + JS 实现文字长阴影

177 阅读2分钟

「这是我参与2022首次更文挑战的第8天,活动详情查看:2022首次更文挑战

前言

这次我们实现的css 效果是文字阴影,先上效果图

Kapture 2022-01-24 at 18.43.06.gif

perspective

实现这个效果的关键就是利用 css 的perspective属性,这个属性的作用是设置3D 子元素被查看位置的视图。当为元素定义 perspective 属性时,其子元素会获得透视效果。也就是说如果你的子元素是 3D元素,那么就可以用 perspective 改变视图距离,且会被变成透视效果。那怎么可以变成3D元素呢,我们可以使用transform 的 rotateX 使元素变成3D。
默认情况下,消失点位于元素的中心,但是可以通过设置perspective-origin属性来改变其位置。

实现

思路:创建两个标签,其中一个用来展示文案,另一个当作这个文案的阴影。通过一个容器把文字和文字的阴影包裹起来,并设置容器的默认 perspective 值

<h1 id="perspective">
  <strong id="shadow">Mega Shadow Text</strong>
  <strong>Mega Shadow Text</strong>
</h1>

css

html, body { margin:0; overflow:hidden; min-height:100%; }
html { position:relative; padding:20px 0 0; }
body { position:absolute; height:100%; width:100%; text-align:center; background:hsl(201,3%,50%); }
#perspective { 
  font:65px "Oswald";
  text-transform:uppercase;
  -webkit-perspective: 100;
  -moz-perspective: 100;
  -ms-perspective: 100;
  perspective: 100;
}

strong {
  display:block;
  position:absolute;
  width:100%;
  text-align:center;
  line-height:58px;
  color:hsl(201,3%,18%);
}

#shadow { 
  transform:rotateX(-110deg);
  transform-origin:center bottom;
  color:transparent;
  user-select:none;
  text-shadow:
    0 0 1px hsla(201,3%,30%,.6),
    0 -7px 10px hsla(201,3%,30%,.3);
}

通过 text-shadowrotateX 把阴影文字设置阴影并变成3D元素。
这时候我们的效果就出来了。

image.png

增加动效

我们可以通过动态设置容器的perspective来达到动画的效果。监听html节点的鼠标移动事件。

document.body.addEventListener('mousemove', (e) => {
  const shadowDom = document.getElementById('shadow');
  var deg = (e.pageY/10)+240;
  var rotation = 'rotateX(' + deg + 'deg)'; 
  shadowDom.style.transform = rotation

  var perspectivedata = (e.pageY/2) + 25;
  const perspectiveDom = document.getElementById('perspective');
  perspectiveDom.style = `
    -webkit-perspective: ${perspectivedata};
    -moz-perspective: ${perspectivedata};
    -ms-perspective: ${perspectivedata};
    perspective: ${perspectivedata};
  `;
})

总结

这个效果可以使用在页面上比较重要的文字上,以此来突出这个文字,