效果 :)
不帶連線效果:
帶連線的效果:
教程
要實(shí)現(xiàn)這樣的效果其實(shí)很簡單,大概分為這么幾個(gè)步驟:
創(chuàng)建canvas
首先需要在需要展示粒子背景的父元素中創(chuàng)建一個(gè)canvas
標(biāo)簽, 指定width
和height
, 在我們生成隨機(jī)點(diǎn)坐標(biāo)的時(shí)候需要用width
和height
來做參照。width
和height
等于父元素的寬和高。
// 假如父元素是bodyconst ele = document.body;const canvas = document.createElement('canvas');canvas.width = ele.clientWidth;canvas.height = ele.clientHeight;// 將canvas標(biāo)簽插入ele.appendChild(canvas);
隨機(jī)生成一定數(shù)量的點(diǎn)坐標(biāo)信息
以width
和height
做參照隨機(jī)生成一定數(shù)量的點(diǎn)坐標(biāo)信息,包含x
, y
, rateX
(點(diǎn)在X軸的移動速率), rateY
(點(diǎn)在Y軸移動的速率), rateX
和rateY
決定了點(diǎn)的運(yùn)動軌跡。
const points = [];// 隨機(jī)生成點(diǎn)的坐標(biāo),需指定radius的最大值function getPoint(radius) { const x = Math.ceil(Math.random() * this.width), // 粒子的x坐標(biāo) y = Math.ceil(Math.random() * this.height), // 粒子的y坐標(biāo) r = +(Math.random() * this.radius).toFixed(4), // 粒子的半徑 rateX = +(Math.random() * 2 - 1).toFixed(4), // 粒子在x方向運(yùn)動的速率 rateY = +(Math.random() * 2 - 1).toFixed(4); // 粒子在y方向運(yùn)動的速率 return { x, y, r, rateX, rateY };}// 隨機(jī)生成100個(gè)點(diǎn)的坐標(biāo)信息for (let i = 0; i < 100; i++) { points.push(this.getPoint());}
將生成的點(diǎn)數(shù)組畫到canvas上
function drawPoints() { points.forEach((item, i) => { ctx.beginPath(); ctx.arc(item.x, item.y, item.r, 0, Math.PI*2, false); ctx.fillStyle = '#fff'; ctx.fill(); // 根據(jù)rateX和rateY移動點(diǎn)的坐標(biāo) if(item.x > 0 && item.x < width && item.y > 0 && item.y < height) { item.x += item.rateX * rate; item.y += item.rateY * rate; } else { // 如果粒子運(yùn)動超出了邊界,將這個(gè)粒子去除,同時(shí)重新生成一個(gè)新點(diǎn)。 points.splice(i, 1); points.push(getPoint(radius)); } });}
畫線
遍歷點(diǎn)數(shù)組,兩兩比較點(diǎn)坐標(biāo),如果兩點(diǎn)之間距離小于某個(gè)值,在兩個(gè)點(diǎn)之間畫一條直線,lineWidth
隨兩點(diǎn)之間距離改變,距離越大,線越細(xì)。
// 計(jì)算兩點(diǎn)之間的距離function dis(x1, y1, x2, y2) { var disX = Math.abs(x1 - x2), disY = Math.abs(y1 - y2); return Math.sqrt(disX * disX + disY * disY);}function drawLines() { const len = points.length; //對圓心坐標(biāo)進(jìn)行兩兩判斷 for(let i = 0; i < len; i++) { for(let j = len - 1; j >= 0; j--) { const x1 = points[i].x, y1 = points[i].y, x2 = points[j].x, y2 = points[j].y, disPoint = dis(x1, y1, x2, y2); // 如果兩點(diǎn)之間距離小于150,畫線 if(disPoint <= 150) { ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.strokeStyle = '#fff'; //兩點(diǎn)之間距離越大,線越細(xì),反之亦然 ctx.lineWidth = 1 - disPoint / distance; ctx.stroke(); } } }}
動畫
使用requestAnimationFrame
循環(huán)調(diào)用draw
方法(draw方法里包含畫點(diǎn)和畫線),同時(shí)在draw
的時(shí)候根據(jù)rateX
和rateY
來改動點(diǎn)的位置。
// 調(diào)用draw函數(shù)開啟動畫(function draw() { ctx.clearRect(0, 0, width, height); drawPoints(); // 如果不需要畫線,取消下面這行代碼即可。 drawLines(); window.requestAnimationFrame(draw);}());
完整代碼請看: https://github.com/PengJiyuan/particle-bg
我的Github:https://github.com/PengJiyuan
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答