您的位置:首页 > Web前端 > HTML5

使用HTML5 Canvas创建动态粒子网格动画

2016-12-13 13:59 881 查看
转载于:http://blog.csdn.net/u014346301/article/details/53608055

最近看到一个粒子网格动画挺炫的,自己也就做了一个,当背景挺不错的。CSDN不能上传超过2M的图片,所以就简单截了一个静态图片:



可以点击这里查看动画.

下面就开始说怎么实现这个效果吧: 

首先当然是添加一个
canvas
了:
<canvas id="canvas"></canvas>
1
1

下面是样式:
<style>
#canvas{
position: absolute;
display: block;
left:0;
top:0;
background: #0f0f0f;
z-index: -1;
}
</style>
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10

上面
canvas
z-index:
-1
的作用是可以放在一些元素的下面当做背景。

为了确保canvas能够充满整个浏览器,所以要将canvas的宽高设置成和浏览器一样:
function getSize(){
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
}
1
2
3
4
1
2
3
4

上面
w
h
分别代表浏览器的宽高。

获得了浏览器的宽高,接下来就是在里面画粒子了,这里我们需要提前定义一些粒子的参数:
var opt = {
particleAmount: 50,         //粒子个数
defaultSpeed: 1,            //粒子运动速度
variantSpeed: 1,            //粒子运动速度的变量
particleColor: "rgb(32,245,245)",       //粒子的颜色
lineColor:"rgb(32,245,245)",            //网格连线的颜色
defaultRadius: 2,           //粒子半径
variantRadius: 2,           //粒子半径的变量
minDistance: 200            //粒子之间连线的最小距离
};
1
2
3
4
5
6
7
8
9
10
1
2
3
4
5
6
7
8
9
10

上面的速度变量和半径变量都是为了保证粒子的大小和速度不是一模一样。

然后我们再创建一个类用来初始化粒子,代码比较长,我都加了注释:
function Partical(){
this.x = Math.random()*w;           //粒子的x轴坐标
this.y = Math.random()*h;           //粒子的y轴坐标
this.speed = opt.defaultSpeed + opt.variantSpeed*Math.random();     //粒子的运动速度
this.directionAngle = Math.floor(Math.random()*360);                //粒子运动的方向
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(){                   //粒子的更新函数
this.border();                           //判断粒子是否到了边界
this.x += this.vector.x;                //粒子下一时刻在x轴的坐标
this.y += this.vector.y;                //粒子下一时刻在y轴的坐标
}
this.border = function(){               //判断粒子是都到达边界
if(this.x >= w || this.x<= 0){      //如果到达左右边界,就让x轴的速度变为原来的负数
this.vector.x *= -1;
}
if(this.y >= h || this.y <= 0){     //如果到达上下边界,就让y轴的速度变为原来的负数
this.vector.y *= -1;
}
if(this.x > w){                     //下面是改变浏览器窗口大小时的操作,改变窗口大小后有的粒子会被隐藏,让他显示出来即可
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(){                 //绘制粒子的函数
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius ,0 ,Math.PI * 2);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

每个粒子的初始速度和角度是随机生成的,粒子的颜色通过相关的设置选项来确定。

this.vector
用来存储粒子的移动方向:如果
this.vector.x
为1,则粒子向右运动;如果是-1,则粒子向左移动。同样,如果
this.vector.y
为负,则粒子向上移动,如果为正,则粒子向下移动。 
this.update
用来更新每个粒子下一个位置的坐标。首先,进行边缘检测;如果粒子的移动超出了
canvas
的尺寸,则将方向向量乘以-1产生反向的运动方向。

窗口缩放可能会引起粒子超出边界,如此一来边缘检测函数就捕捉不到了,所以就需要一系列的if语句来检测这种情况,将粒子的位置重置为当前
canvas
的边界。

最后一步,将这些点绘制到画布上。

粒子的类已经写好了,下面就把他绘制出来:
function init(){
getSize();
for(let i = 0;i<opt.particleAmount; i++){
particle.push(new Partical());
}
loop();
}
1
2
3
4
5
6
7
1
2
3
4
5
6
7

上面初始化了
opt.particleAmount
个粒子对象,初始化了对象但是并没有绘制出来,下面是
loop
函数:
function loop(){
ctx.clearRect(0,0,w,h);
for(let i = 0;i<particle.length; i++){
particle[i].update();
particle[i].draw();
}
window.requestAnimationFrame(loop);
}
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8

loop()
函数每执行一次,都会清除
canvas
上的内容,然后通过粒子对象的
update()
函数重新计算粒子的坐标,最后通过粒子对象的
draw()
函数来绘制粒子。下面是这个时候的效果:



但是在浏览器窗口大小改变以后有些粒子就会消失不见,这个时候需要添加一个事件来监听浏览器大小是否改变:
window.addEventListener("resize",function(){
winResize()
},false);
1
2
3
1
2
3

然后需要来写
winResize()
函数,这里需要注意一下,浏览器改变的时候触发
resize
事件的次数会特别频繁,稍微移动一下浏览器的边缘就是触发几十次
resize
事件,那么也就会重新计算几十次浏览器大小,比较消耗性能,这个大家可以测试一下,这里就直接说解决方法吧,其实我们要的只是浏览器改变后的最后的大小,至于中间到底改变了多少次和我们没有关系,所以我们可以在浏览器窗口改变的时候延缓200毫秒后执行计算浏览器大小的事件,如果在这期间一直触发resize事件,那就一直往后延缓200毫秒,听起来挺复杂,其实代码很简单:
var particle = [], w,h;     //粒子数组,浏览器宽高
var delay = 200,tid;        //延缓执行事件和setTimeout事件引用
function winResize(){
clearTimeout(tid);
tid = setTimeout(function(){
getSize();          //获取浏览器宽高,在文章最上面有介绍
},delay)
}
1
2
3
4
5
6
7
8
1
2
3
4
5
6
7
8

这样所有的粒子动画都完成了,接下来就可以在粒子之间画线了,我们上面定义的opt对象里面有一个minDistance变量,当两个粒子之间的连线小于这个值的时候,我们就给他们之间画上线。

那么如何计算两个粒子之间的距离呢,大家可以回想一下初中数学第一课,勾股定理,直角三角形两个直角边的平方和等于第三条变的平方,看下面: 



我们现在知道每个粒子的x轴和y轴的坐标,那么我们就可以计算出两个点之间的距离了,写一个函数,传入两个点,如下:
function getDistance(point1,point2){
return Math.sqrt(Math.pow(point1.x-point2.x,2) + Math.pow(point1.y - point2.y ,2));
}
1
2
3
1
2
3

现在我们可以计算出两个点的距离,那么我们就计算出所有每个粒子同其他所有粒子的距离,来确定它们之间是否需要连线,当然如果所有粒子的颜色深度都一模一样,那就有点丑了,所以我们这里可以根据两个粒子之间的距离来决定连线的透明度,两个粒子距离越近,越不透明,距离越远,越透明,超过一定距离就不显示了。
function linePoint(point,hub){
for(let i = 0;i<hub.length;i++){
let distance = getDistance(point,hub[i]);
let opacity = 1 -distance/opt.minDistance;
if(opacity > 0){
ctx.lineWidth = 0.5;
ctx.strokeStyle = "rgba("+line[0]+","+line[1]+","+line[2]+","+opacity+")";
ctx.beginPath();
ctx.moveTo(point.x,point.y);
ctx.lineTo(hub[i].x,hub[i].y);
ctx.closePath();
ctx.stroke();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

上面传入的两个参数分别是一个点和整个点的数组,
let opacity = 1 -distance/opt.minDistance;
用于判断连线之间的透明度同时也判断了距离,距离大于
opt.minDistance
时,opacity为负,下面判断时就过滤掉了,上面的颜色用到了正则表达式,需要先解析最上面opt对象里给出的颜色,然后再加上透明度,这段代码如下:
var line = opt.lineColor.match(/\d+/g);
1
1

最后在
loop()
函数里面不断循环计算距离就可以了,在
loop()
中加入代码后如下:
function loop(){
ctx.clearRect(0,0,w,h);
for(let i = 0;i<particle.length; i++){
particle[i].update();
particle[i].draw();
}
for(let i = 0;i<particle.length; i++){   //添加的是这个循环
linePoint(particle[i],particle)
}
window.requestAnimationFrame(loop);
}
1
2
3
4
5
6
7
8
9
10
11
1
2
3
4
5
6
7
8
9
10
11

需要指出的是:如果添加过多的点和/或过多的连接距离(连接距离会创建过多的线条),动画也会扛不住。当视口变窄时最好降低粒子的运动速度:粒子的尺寸越小,在愈加狭窄空间内的移动速度貌似会越快。

显示整段代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas粒子动画</title>
<style> #canvas{ position: absolute; display: block; left:0; top:0; background: #0f0f0f; z-index: -1; } </style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var opt = {
particleAmount: 50, //粒子个数
defaultSpeed: 1, //粒子运动速度
variantSpeed: 1, //粒子运动速度的变量
particleColor: "rgb(32,245,245)", //粒子的颜色
lineColor:"rgb(32,245,245)", //网格连线的颜色
defaultRadius: 2, //粒子半径
variantRadius: 2, //粒子半径的变量
minDistance: 200 //粒子之间连线的最小距离
};
var line = opt.lineColor.match(/\d+/g);
console.log(line);
var particle = [], w,h;
var delay = 200,tid;
init();
window.addEventListener("resize",function(){ winResize() },false);

function winResize(){
clearTimeout(tid);
tid = setTimeout(function(){
getSize();
},delay)
}

function init(){ getSize(); for(let i = 0;i<opt.particleAmount; i++){ particle.push(new Partical()); } loop(); }

function loop(){
ctx.clearRect(0,0,w,h);
for(let i = 0;i<particle.length; i++){
particle[i].update();
particle[i].draw();
}
for(let i = 0;i<particle.length; i++){
linePoint(particle[i],particle)
}
window.requestAnimationFrame(loop);
}

function linePoint(point,hub){ for(let i = 0;i<hub.length;i++){ let distance = getDistance(point,hub[i]); let opacity = 1 -distance/opt.minDistance; if(opacity > 0){ ctx.lineWidth = 0.5; ctx.strokeStyle = "rgba("+line[0]+","+line[1]+","+line[2]+","+opacity+")"; ctx.beginPath(); ctx.moveTo(point.x,point.y); ctx.lineTo(hub[i].x,hub[i].y); ctx.closePath(); ctx.stroke(); } } }

function getDistance(point1,point2){ return Math.sqrt(Math.pow(point1.x-point2.x,2) + Math.pow(point1.y - point2.y ,2)); }

function getSize(){ w = canvas.width = window.innerWidth; h = canvas.height = window.innerHeight; }
function Partical(){ this.x = Math.random()*w; //粒子的x轴坐标 this.y = Math.random()*h; //粒子的y轴坐标 this.speed = opt.defaultSpeed + opt.variantSpeed*Math.random(); //粒子的运动速度 this.directionAngle = Math.floor(Math.random()*360); //粒子运动的方向 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(){ //粒子的更新函数 this.border(); //判断粒子是否到了边界 this.x += this.vector.x; //粒子下一时刻在x轴的坐标 this.y += this.vector.y; //粒子下一时刻在y轴的坐标 } this.border = function(){ //判断粒子是都到达边界 if(this.x >= w || this.x<= 0){ //如果到达左右边界,就让x轴的速度变为原来的负数 this.vector.x *= -1; } if(this.y >= h || this.y <= 0){ //如果到达上下边界,就让y轴的速度变为原来的负数 this.vector.y *= -1; } if(this.x > w){ //下面是改变浏览器窗口大小时的操作,改变窗口大小后有的粒子会被隐藏,让他显示出来即可 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(){ //绘制粒子的函数 ctx.beginPath(); ctx.arc(this.x, this.y, this.radius ,0 ,Math.PI * 2); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); } }
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: