CSS实现光照效果

(24) 2024-01-25 09:12

Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说CSS实现光照效果,希望能够帮助你!!!。

先来看下效果:

CSS实现光照效果_https://bianchenghao6.com/blog__第1张

可以看到,光标的位置像一个手电筒一样照着,这就是今天我们要实现的光照效果,主要代码如下:

// html 代码
<div class="box">
  <div class="effect"></div>
  <div class="item-list">
    <div class="flex-row item-list-row">
      <div class="flex-side flex-row item">
        <div class="flex-side icon"></div>
        <div class="flex-main">
          <div class="name">系统</div>
          <div class="desc">显示、声音、通知、电源</div>
        </div>
      </div>
    </div>
  </div>
</div>
// CSS代码
.flex-row {
  display: -webkit-flex;
  display: flex;
  -webkit-flex-direction: row;
  flex-direction: row;
}

.box {
  position: relative;
  display: inline-block;
  color: #fff;
  font-size: 20px;
  background-color: #000;
  --pt-x: 0;
  --pt-y: 0;
}

.box .effect {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: radial-gradient(
    circle at calc(var(--pt-x) * 1px) calc(var(--pt-y) * 1px),
    #fff,
    rgba(255, 255, 255, 0) 4em
  );
  z-index: 0;
}


.box .item-list {
  z-index: 2;
}
.box .item-list .item {
  position: relative;
  margin: 1em;
  padding: 1em;
  line-height: 1.5em;
  border: 2px solid rgba(255, 255, 255, 0.5);
  background-color: rgba(0, 0, 0, 0.7);
  background-clip: padding-box;
  box-shadow: 0 0 0 1em #000;
}

.box .item-list .item .icon {
  margin-right: 1em;
  width: 1.5em;
  height: 1.5em;
  background-color: rgba(255, 255, 255, 0.5);
}

.box .item-list .item .desc {
  color: #999;
  font-size: 16px;
}

然后是几行javascript代码:

document.addEventListener("DOMContentLoaded", function () {
  let domBox = document.querySelector(".box");
  domBox.addEventListener("mousemove", function ($evt) {
    let rect = domBox.getBoundingClientRect();
    domBox.style.setProperty("--pt-x", $evt.pageX - rect.left);
    domBox.style.setProperty("--pt-y", $evt.pageY - rect.top);
  });
});

稍微讲解下原理,首先样式的效果主要是在<div class="effect"></div>这个标签上设置的,然后设置样式为absolute绝对定位,就相当于父级元素的蒙层,背景颜色是一个径向渐变,大概是这样:

.box-effect {
  margin-top: 20px;
  border: 1px solid black;
  width: 310px;
  height: 120px;
  background: radial-gradient(    #fff,
    rgba(0, 0, 0, 1) 4em);
}
CSS实现光照效果_https://bianchenghao6.com/blog__第2张

javascript代码就是获取鼠标的位置,然后把上面径向渐变的中心点实时修改成鼠标的位置,大概就是这样:

CSS实现光照效果_https://bianchenghao6.com/blog__第3张

最后,调整CSS将光照涂层和另一个图层合并,效果就实现了,CSS调整大致就是z-index,position和背景色rgba的设置,具体就不讲解了,远离大概就是这样了。

今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

上一篇

已是最后文章

下一篇

已是最新文章

发表回复