canvas粒子动画背景的实现示例

2020-04-21 22:45:12易采站长站整理

效果 ????

不带连线效果:

带连线的效果:

教程

要实现这样的效果其实很简单,大概分为这么几个步骤:

创建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();