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

手把手教你系列 - Particle粒子特效(上)

2017-09-18 08:44 337 查看
本着瞎折腾的学习态度,在闲暇之余就是要搞点奇奇怪怪的事情。文中如有哪不对的地方,还请大家指出。本文项目github地址:https://github.com/SmallStoneSK/particle-effect

前言

今天要跟大家一起分享的是最近用canvas写的一个Particle粒子特效,这效果是很早就出现过了,所以想必大家应该都见到过(没见过的看下面的gif图,或者戳演示地址,或者直接看知乎首页



以前第一次见到的时候,心想:哇靠,那么炫酷,这是怎么实现的?于是开始想各种可能的实现方案,但是却从来没有真正地去实现一次。最近闲下来之后又想到了这个特效,手痒就折腾了下,在这儿跟大家分享一下(代码中有哪不对的地方,欢迎拍砖,我改还不行吗…)。

动手前的思考

在动手前,不妨先思考一下这效果是怎么实现的呢?有两种方式:dom 或 canvas。

第一种dom方法,我们可以把页面上的粒子看做是一个个通过绝对定位布局的div,然后用定时器不断改变它们在页面中的top和left值,这样就可以模拟出粒子运动的效果。但是我们都知道对dom的操作是很耗性能的,如果粒子的数量少的话可能还好,但要是碰到个逗逼(比如像我这样的)把粒子的数量设的超级大,那对浏览器来说,性能方面肯定是个顾虑。所以出于性能考虑,这种方法果断弃之。

第二种方法是用canvas来实现。想必大家都知道canvas是干嘛用的,其实说白了就是给你一块画布,然后你想怎么画就怎么画。那么对应到本文中要实现的这个Particle粒子特效,是不是只要把这个动画的每一帧都画出来就可以了?而要画出每一帧,是不是只要把这个场景中的所有元素对应到画布中的具体位置画出来就可以了?其实用canvas实现的一些动画、游戏的原理大抵都是如此。为了便于大家的理解,不妨瞅一眼下面的伪代码:

while(true) {

// 清除上一帧
clearLastFrame();

// 绘制(Particle粒子特效的绘制包括drawParticle和drawLine)
draw();

// 延迟16.7s(对于人的肉眼而言,1秒60帧的动画就可以)
sleep(1000/60);
}


实现设计

既然已经明确使用canvas来实现我们的Particle粒子特效,那在具体实现之前,我们不妨先来捋一捋整个过程。

1. init初始化

第一步:在html的body中先插入一个带id的canvas标签,以便在js中找到它。

<canvas id="canvas">
<p>your browser doesn't support canvas.</p>
</canvas>


* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
background-color: #292d35;
}


第二步:新建一个ParticleEffect.js文件,添加一个init方法,需要设置canvas的宽高,获取canvas的上下文。

// 粒子特效
var ParticleEffect = {
ctx: null,
canvas: null,
init: function() {

var windowSize = Utils.getWindowSize();  // 获取窗口大小
this.canvas = document.getElementById('canvas');
this.ctx = this.canvas.getContext('2d');

if(this.ctx) {

// 设置canvas的宽高
this.canvas.width = windowSize.width;
this.canvas.height = windowSize.height;

// 在这里,你就可以开始用ctx随心所欲的画画了
}
}
};

// 工具
var Utils = {
getWindowSize: function() {
return {
width: this.getWindowWidth(),
height: this.getWindowHeight()
};
},
getWindowWidth: function() {
return window.innerWidth || document.documentElement.clientWidth;
},
getWindowHeight: function() {
return window.innerHeight || document.documentElement.clientHeight;
}
};


2.构造Particle类

我们会利用工厂模式创造一个Particle类,给每个粒子都添加以下属性:

// 粒子类
function Particle(info) {

// 粒子属性
this.x = info.x;            // 粒子在画布中的横坐标
this.y = info.y;            // 粒子在画布中的纵坐标
this.vx = info.vx;          // 粒子的横向运动速度
this.vy = info.vy;          // 粒子的纵向运动速度
this.color = info.color;    // 粒子的颜色
this.scale = info.scale;    // 粒子的缩放比例
this.radius = info.radius;  // 粒子的半径大小

// 绘制方法
if(typeof Particle.prototype.draw === 'undefined') {
Particle.prototype.draw = function(ctx) {
// canvas画圆方法
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.strokeStyle = this.color;
ctx.arc(this.x, this.y, this.radius * this.scale, 0, 2 * Math.PI, false);
ctx.closePath();
ctx.fill();
}
}
}


3.生成粒子

现在我们就可以在init方法中用刚创建好的Particle类来生成我们的粒子了。这里还有一点需要注意的就是,为了模拟粒子运动的真实性,我们就得随机的赋予粒子的各个属性,包括横坐标、纵坐标、横向速度、纵向速度、半径、缩放比例。具体的就看下面代码吧:

var ParticleEffect = {
// ... 省去其他代码
init: function() {

// ... 省去其他代码

if(this.ctx) {

// ... 省去其他代码

// 生成100个粒子(这里需要注意的是,由于粒子是有半径的,所以初始的x, y值范围需要相应的调整)
var times = 100;
this.particles = [];
while(times--) {
this.particles.push(new Particle({
x: Utils.rangeRandom(10, windowSize.width - 10),
y: Utils.rangeRandom(10, windowSize.height - 10),
vx: Utils.rangeRandom(-1.2, 1.2),
vy: Utils.rangeRandom(-1.2, 1.2),
color: 'rgba(255,255,255,.2)',
scale: Utils.rangeRandom(0.8, 1.2),
radius: 10
}));
}
}
}
};

var Utils = {
... // 省去其他代码
rangeRandom: function(min, max) {
const diff = max - min;
return min + Math.random() * diff;
}
};


4.让粒子动起来

终于到了激动人心的时候了,在这一步中,我们就让粒子满屏的动起来。

第一步:添加move方法,更新粒子的x, y坐标。需要注意的是,在每次更新完粒子的坐标以后,需要检测是否有碰到墙壁。如果有的话,需要改变粒子的运动方向。

var ParticleEffect = {
// ... 省去其他代码
move: function() {

var windowSize = Utils.getWindowSize();

this.particles.forEach(function(item) {

// 更新粒子坐标
item.x += item.vx;
item.y += item.vy;

// 如果粒子碰到了左墙壁或右墙壁,则改变粒子的横向运动方向
if((item.x - item.radius < 0) || (item.x + item.radius > windowSize.width)) {
item.vx *= -1;
}

// 如果粒子碰到了上墙壁或下墙壁,则改变粒子的纵向运动方向
if((item.y - item.radius < 0) || (item.y + item.radius > windowSize.height)) {
item.vy *= -1;
}
});
}
};


第二步:添加draw方法,控制canvas每次绘制的内容(我们先不绘制粒子之间的连线,先让粒子动起来看到效果)。

var ParticleEffect = {
// ... 省去其他代码
draw: function() {

var _this = this;

// 每次重新绘制之前,需要先清空画布,把上一次的内容清空
this.ctx.clearRect(0, 0, windowSize.width, windowSize.height);

// 绘制粒子
this.particles.forEach(function(item) {
item.draw(_this.ctx);
});

// TODO: 绘制粒子之间的连线

// 粒子移动,更新相应的x, y坐标
this.move();
}
};


第三步:添加run方法,使用定时器,不断重新绘制canvas上的内容

var ParticleEffect = {
// ... 省去其他代码
run: function() {
this.init();
setInterval(this.draw.bind(this), 1000 / 60);
}
};


第四步:到这儿就是调用了,调用下Particle.run方法就可以让满屏的粒子动起来了。

<body>
<canvas id="canvas"> <p>your browser doesn't support canvas.</p> </canvas>
<script src="./Particle.js"></script>
<script>
window.onload = function() {
ParticleEffect.run();
};
</script>
</body>


5.回过头来绘制粒子之间的线条

通过观察不难发现,在粒子运动的过程中,两个粒子之间的距离比较远的时候是不相连的,只有当两个粒子运动到一定距离范围之内才会相连,而远了之后细线又会断开。所以实现起来也不难,只要遍历所有粒子之间的距离,只要小于一个阈值,我们就用canvas画一条线,把这两个粒子连接起来。具体代码如下:

var ParticleEffect = {
// ... 省去其他代码
draw: function() {

// ... 省去其他代码

// 绘制粒子之间的连线
for(var i = 0; i < this.particles.length; i++) {
for(var j = i + 1; j < this.particles.length; j++) {
var distance = Math.sqrt(Math.pow(this.particles[i].x - this.particles[j].x, 2) + Math.pow(this.particles[i].y - this.particles[j].y, 2));
if(distance < 100) {
// 这里我们让距离远的线透明度淡一点,距离近的线透明度深一点
this.ctx.strokeStyle = 'rgba(255,255,255,' + (distance / 100 * .2) + ')';
this.ctx.beginPath();
this.ctx.moveTo(this.particles[i].x, this.particles[i].y);
this.ctx.lineTo(this.particles[j].x, this.particles[j].y);
this.ctx.closePath();
this.ctx.stroke();
}
}
}

}
};


6.添加粒子与鼠标之间的连线

其实完成上面的这个步骤,粒子特效已经基本上能跑了。但是我们还可以再添加粒子跟鼠标之间的交互效果,比如当鼠标与粒子之间的距离小于一定阈值时,连接粒子与鼠标。话不多说,看下面的代码:

var ParticleEffect = {
// ... 省去其他代码
mouseCoordinates: {x: 0, y: 0},
init: function() {

// ... 省去其他代码

// 监听鼠标的mouseMove事件,记录下鼠标的x,y坐标
window.addEventListener('mousemove', this.handleMouseMove.bind(this), false);
},
draw: function() {

// ... 省去其他代码

// 绘制粒子和鼠标之间的连线
for(i = 0; i < this.particles.length; i++) {
distance = Math.sqrt(Math.pow(this.particles[i].x - this.mouseCoordinates.x, 2) + Math.pow(this.particles[i].y - this.mouseCoordinates.y, 2));
if(distance < 100) {
this.ctx.strokeStyle = 'rgba(255,255,255,' + (1 - distance / 100) * .3 + ')';
this.ctx.beginPath();
this.ctx.moveTo(this.particles[i].x, this.particles[i].y);
this.ctx.lineTo(this.mouseCoordinates.x, this.mouseCoordinates.y);
this.ctx.closePath();
this.ctx.stroke();
}
}
},
handleMouseMove: function(event) {

var x, y;
event = event || window.event;

// 处理兼容
if(event.pageX || event.pageY) {
x = event.pageX;
y = event.pageY;
} else {
x = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}

this.mouseCoordinates = {x: x, y: y};
}
};


未完,待续…

其实做到这儿,已经能够看到效果了。但是,还有还有很多可以进一步优化的地方。比如:粒子动效的参数可配置化,canvas自适应窗口大小,requestAnimationFrame代替setInterval,缓存windowSize等等… 这些内容将在下一章中再做介绍。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息