在vue中通過backdrop-filter實現漸變的高斯模糊


一、需求分析

當用戶向上滾動屏幕后,我們希望上方的圖片可以有漸變的模糊效果
也就是說 我們需要:
1、監聽頁面的滾動
2、計算模糊度關於滾動距離的函數
3、設置DOM元素的高斯模糊

二、關於backdrop-filter

這個CSS屬性的作用是:對元素后面的所有內容應用過濾效果

<template>
  <div class="bg-image"  ref="bgImage">
      <div class="filter" ref="filter"></div>
  </div>
</template>

注意:元素本身或其背景需要設置一定的透明度

<style scoped lang="stylus">
.filter
  background: rgba(7, 17, 27, 0.4)
</style>

關於backdrop-filter屬性的更多取值可以參考MDN官方文檔

三、具體實現過程

當用戶開始滾動屏幕時,會觸發scroll事件
通過已經封裝好的better-scroll組件,傳入參數pos
將pos.y賦值給this.scrollY

methods: {
    scroll(pos) {
      this.scrollY = pos.y
    }
}

通過watch監聽scrollY的變化
初始化變量 blur=0
設置變量percent 為 scroolY與圖片絕對高度(ImageHeight)的比值
使得blur從0開始,隨着|scrollY|變大而變大,直到20px

watch:{
  scrollY(newY) {
    let blur = 0
    const percent = Math.abs(newY/ this.ImageHeight)

    if (newY<=0) {
      blur =  Math.min(20 * percent, 20)
    }

    this.$refs.filter.style['backdrop-filter'] = `blur(${blur}px)`
    this.$refs.filter.style['webkitBackdrop-filter'] = `blur(${blur}px)`
  }
}

最終效果如下:
gif6.gif


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM