先給大家看個效果圖(截圖自pohutech.com,這是我寫的第一個網站)css
其實原理很簡單,就是將波函數樣式表現出來,我先簡單說下波函數git
我這裏採起的實現方式是經過css屬性background-image實現的。github
class Wave {
constructor(position, startTime, duration = 5000, angular_speed = 20) {
this.position = position;
this.startTime = startTime;
this.stopId = 0;
//水波持續時間 默認5000ms
this.duration = duration;
this.angular_speed = angular_speed;
}
}
複製代碼
類Wave中最重要的方法bash
shuffle (element){
let data = [];
//設置滿屏的週期數,即水波的密集程度,我這設置爲10
for (let i = 0; i < 100; i++) {
data.push(Math.PI / 5 * (i + 1));
}
//記錄水波的做用時間
let dt = new Date() - this.startTime;
if (dt > this.duration){
this.stopMove();
return;
}
let height = data.map(
(value) => {
let x = value - this.angular_speed * dt / 1000;
//x<0時,波尚未傳播到那裏,h=0
//sinx的取值範圍爲[-1,1],將其轉化爲[0,0.5]
let h = x < 0 ? (Math.sin(x)+1)/4 : 0.25;
return h;
}
)
let bg = "radial-gradient(circle at ";
bg += `${this.position.px}px ${this.position.py}px`;
height.forEach(function (value,index) {
//顏色能夠自取,我這裏取了rgb(192,85,181),而後經過透明度表現出波函數
//你能夠嘗試在顏色重加入時間變化
//(100-index)/100表示隨距離係數
//(this.duration-dt)/this.duration表示時間衰減係數
bg += `,rgba(192,85,181,${value*(100 - index) / 100 * (this.duration - dt) / this.duration}) ${index + 1}%`;
}.bind(this));
bg += ")";
//注意element.style.backgroundImage = 'radial-gradient……'沒有效果!這應該是原生dom一個bug.
element.setAttribute("style", `width:100vw;height:100vh;position:fixed;z-index:100;top:0px;left:0px;background-image: ${bg};`);
console.info(element);
//由於requestAnimationFrame(function)默認傳參time,沒辦法實現咱們要的傳遞element,因此封裝了一下
//記得要綁定this,否則第二次執行shuffle就彙報this is not define!
this.stopId = requestAnimationFrame(function (){this.shuffle(element)}.bind(this));
}
複製代碼
還有一個方法是取消動畫:app
stopMove() {
cancelAnimationFrame(this.stopId);
this.stopId = 0;
}
複製代碼
onload = () => {
document.querySelector("body").onclick = (event) => {
let covering = document.createElement("div");
const position = {};
//解構賦值
[position.px, position.py] = [event.clientX, event.clientY]
let wave = new Wave(position, new Date())
document.querySelector("body").appendChild(covering);
wave.shuffle(covering);
//5秒後,將這個蒙皮移出dom
setTimeout(()=>document.querySelector("body").removeChild(covering),5000);
}
}
複製代碼
如今咱們已經寫完了這個js波函數插件,讓咱們看下效果dom
所有源碼能夠看個人GitHub github.com/jack-shangh… 若是你以爲你個效果不錯,麻煩幫忙點個贊,幫幫我這天涯淪落人。大家只須要看js代碼就夠了。函數