前端 聚光灯效果demo

306 阅读1分钟

针对聚光灯打开时剩余部分依旧遮罩显示的需求,记录此demo

参考文章:juejin.cn/post/714697…

结构: 1、底部为遮罩展示的相对定位内容。 2、上层覆盖绝对定位的相同内容,使用clip-path裁剪为自定义区域内容。

缺陷: 对于复杂页面(如游戏画面),使用时需要上下两层相同内容,此时加载的资源和请求会造成很多消耗。

<template>
  <div class="test">
    <div class="mask">
      <img class="img" :src="img" />
    </div>
    <div class="Spotlight" :style="'clip-path: circle(100px at '+offsetX+' '+offsetY+')'">
      <img class="img" :src="img" />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      img: 'https://upload-images.jianshu.io/upload_images/15201108-84c0254196053be7.png',
      offsetX:0,
      offsetY:0
    }
  },
  mounted() {
    window.addEventListener('mousemove',this.handle)
  },
  beforeDestroy(){
    window.removeEventListener('mousemove',this.handle)
  },
  methods: {
    handle(e){
      this.$nextTick(()=>{
        this.offsetX = e.clientX + 'px'
        this.offsetY = e.clientY + 'px'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.test{
  width: 100%;
  height: 100vh;
  position: relative;
  .mask{
    width: 100%;
    height: 100%;
    position: relative;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: center;
    &::after{
      content: '';
      position: absolute;
      z-index: 2;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5);
    }
  }
  .img{
    width: 600px;
    height: 600px;
    display: block;
    position: relative;
    z-index: 1;
  }
  .Spotlight{
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 3;
    background: #fff;
  }
}
</style>