今天小編教大家學習下 canvas ——粒子動畫背景。
(是不是覺得很炫酷!)
下面我們進入正題,一步一步來教大家學會這個粒子動畫背景。
創建canvas
首先需要在需要展示粒子背景的父元素中創建一個canvas標籤, 指定width和height, 在我們生成隨機點座標的時候需要用width和height來做參照。width和height等於父元素的寬和高。
代碼如下
// 假如父元素是body
const ele = document.body;
const canvas = document.createElement('canvas');
canvas.width = ele.clientWidth;
canvas.height = ele.clientHeight;
// 將canvas標籤插入
ele.appendChild(canvas);
隨機生成一定數量的點座標信息
以width和height做參照隨機生成一定數量的點座標信息,包含x, y, rateX(點在X軸的移動速率), rateY(點在Y軸移動的速率), rateX和rateY決定了點的運動軌跡。
代碼如下
const points = [ ];
// 隨機生成點的座標,需指定radius的最大值
function getPoint(radius) {
const x = Math.ceil(Math.random() * this.width), // 粒子的x座標
y = Math.ceil(Math.random() * this.height), // 粒子的y座標
r = +(Math.random() * this.radius).toFixed(4), // 粒子的半徑
rateX = +(Math.random() * 2 - 1).toFixed(4), // 粒子在x方向運動的速率
rateY = +(Math.random() * 2 - 1).toFixed(4); // 粒子在y方向運動的速率
return { x, y, r, rateX, rateY };
}
// 隨機生成100個點的座標信息
for (let i = 0; i < 100; i++) {
points.push(this.getPoint());
}
將生成的點數組畫到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( );
// 根據rateX和rateY移動點的座標
if(item.x > 0 && item.x < width && item.y > 0 && item.y < height) {
item.x += item.rateX * rate;
item.y += item.rateY * rate;
} else {
// 如果粒子運動超出了邊界,將這個粒子去除,同時重新生成一個新點。
points.splice(i, 1);
points.push(getPoint(radius));
}
});
}
(不連線預覽)
畫線
遍歷點數組,兩兩比較點座標,如果兩點之間距離小於某個值,在兩個點之間畫一條直線, lineWidth 隨兩點之間距離改變,距離越大,線越細。大家可以聯想到初中學過的勾股定理。
代碼如下
// 計算兩點之間的距離
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;
//對圓心座標進行兩兩判斷
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);
// 如果兩點之間距離小於150,畫線
if(disPoint <= 150) {
ctx.beginPath( );
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.strokeStyle = '#fff';
//兩點之間距離越大,線越細,反之亦然
ctx.lineWidth = 1 - disPoint / distance;
ctx.stroke( );
}
}
}
}
(連線預覽)
動畫
使用 requestAnimationFrame 循環調用draw方法(draw方法裡包含畫點和畫線),同時在 draw 的時候根據 rateX 和rateY 來改動點的位置。
代碼如下
// 調用draw函數開啟動畫
(function draw( ) {
ctx.clearRect(0, 0, width, height);
drawPoints( );
// 如果不需要畫線,取消下面這行代碼即可。
drawLines( );
window.requestAnimationFrame(draw);
}( ) );
學會上面的幾個步驟,你就能自己製作一個canvas粒子背景了,趕緊去試試呀,還有什麼疑問可以私信小編"666"
閱讀更多 WEB前端交流 的文章