最近看到一個(gè)粒子網(wǎng)格動(dòng)畫挺炫的,自己也就做了一個(gè),當(dāng)背景挺不錯(cuò)的。CSDN不能上傳超過(guò)2M的圖片,所以就簡(jiǎn)單截了一個(gè)靜態(tài)圖片:
下面就開始說(shuō)怎么實(shí)現(xiàn)這個(gè)效果吧:
首先當(dāng)然是添加一個(gè)canvas了:
<canvas id="canvas"></canvas>
下面是樣式:
<style> #canvas{ position: absolute; display: block; left:0; top:0; background: #0f0f0f; z-index: -1; } </style>
上面canvas的z-index: -1的作用是可以放在一些元素的下面當(dāng)做背景。
為了確保canvas能夠充滿整個(gè)瀏覽器,所以要將canvas的寬高設(shè)置成和瀏覽器一樣:
function getSize(){ w = canvas.width = window.innerWidth; h = canvas.height = window.innerHeight; }
上面w和h分別代表瀏覽器的寬高。
獲得了瀏覽器的寬高,接下來(lái)就是在里面畫粒子了,這里我們需要提前定義一些粒子的參數(shù):
var opt = { particleAmount: 50, //粒子個(gè)數(shù) defaultSpeed: 1, //粒子運(yùn)動(dòng)速度 variantSpeed: 1, //粒子運(yùn)動(dòng)速度的變量 particleColor: "rgb(32,245,245)", //粒子的顏色 lineColor:"rgb(32,245,245)", //網(wǎng)格連線的顏色 defaultRadius: 2, //粒子半徑 variantRadius: 2, //粒子半徑的變量 minDistance: 200 //粒子之間連線的最小距離 };
上面的速度變量和半徑變量都是為了保證粒子的大小和速度不是一模一樣。
然后我們?cè)賱?chuàng)建一個(gè)類用來(lái)初始化粒子,代碼比較長(zhǎng),我都加了注釋:
function Partical(){ this.x = Math.random()*w; //粒子的x軸坐標(biāo) this.y = Math.random()*h; //粒子的y軸坐標(biāo) this.speed = opt.defaultSpeed + opt.variantSpeed*Math.random(); //粒子的運(yùn)動(dòng)速度 this.directionAngle = Math.floor(Math.random()*360); //粒子運(yùn)動(dòng)的方向 this.color = opt.particleColor ; //粒子的顏色 this.radius = opt.defaultRadius+Math.random()*opt.variantRadius; //粒子的半徑大小 this.vector = { x:this.speed * Math.cos(this.directionAngle), //粒子在x軸的速度 y:this.speed * Math.sin(this.directionAngle) //粒子在y軸的速度 } this.update = function(){ //粒子的更新函數(shù) this.border(); //判斷粒子是否到了邊界 this.x += this.vector.x; //粒子下一時(shí)刻在x軸的坐標(biāo) this.y += this.vector.y; //粒子下一時(shí)刻在y軸的坐標(biāo) } this.border = function(){ //判斷粒子是都到達(dá)邊界 if(this.x >= w || this.x<= 0){ //如果到達(dá)左右邊界,就讓x軸的速度變?yōu)樵瓉?lái)的負(fù)數(shù) this.vector.x *= -1; } if(this.y >= h || this.y <= 0){ //如果到達(dá)上下邊界,就讓y軸的速度變?yōu)樵瓉?lái)的負(fù)數(shù) this.vector.y *= -1; } if(this.x > w){ //下面是改變?yōu)g覽器窗口大小時(shí)的操作,改變窗口大小后有的粒子會(huì)被隱藏,讓他顯示出來(lái)即可 this.x = w; } if(this.y > h){ this.y = h; } if(this.x < 0){ this.x = 0; } if(this.y < 0){ this.y = 0; } } this.draw = function(){ //繪制粒子的函數(shù) ctx.beginPath(); ctx.arc(this.x, this.y, this.radius ,0 ,Math.PI * 2); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); } }
1、每個(gè)粒子的初始速度和角度是隨機(jī)生成的,粒子的顏色通過(guò)相關(guān)的設(shè)置選項(xiàng)來(lái)確定。
2、this.vector用來(lái)存儲(chǔ)粒子的移動(dòng)方向:如果this.vector.x為1,則粒子向右運(yùn)動(dòng);如果是-1,則粒子向左移動(dòng)。同樣,如果this.vector.y為負(fù),則粒子向上移動(dòng),如果為正,則粒子向下移動(dòng)。
this.update用來(lái)更新每個(gè)粒子下一個(gè)位置的坐標(biāo)。首先,進(jìn)行邊緣檢測(cè);如果粒子的移動(dòng)超出了canvas的尺寸,則將方向向量乘以-1產(chǎn)生反向的運(yùn)動(dòng)方向。
3、窗口縮放可能會(huì)引起粒子超出邊界,如此一來(lái)邊緣檢測(cè)函數(shù)就捕捉不到了,所以就需要一系列的if語(yǔ)句來(lái)檢測(cè)這種情況,將粒子的位置重置為當(dāng)前canvas的邊界。
4、最后一步,將這些點(diǎn)繪制到畫布上。