如果经常上网就一定见过一些博客的背景有一些粒子跑来跑去,还可以连线。看着是挺炫酷的。基本上就类似上面的效果。今天终于用代码敲出来了,虽然过程不是太顺利,就是粒子跟随鼠标那个效果,我怎么都想不到实现思路。还好最后死想出来了,用的方法虽然挺笨的。
这个效果一直是我想做的,在我玩 HEXO 搭建个人博客的时候,参考了很多人的网页其中见到效果最多的就是这个,当时就暗暗下决心我的把它给写出来,但那时候我觉得老难了,啥思路没有,毕竟那时候的我知识储备不够,而且当时主要学习理论为主要,实践的东西很少。
现在的我虽然不是很大神,但是可是能用canvas写出来游戏的学生,绝大多数canvas的效果我都是能做出来的,还是很厉害滴。字数够了,开始正文,再讲下去怕被打。。。
使用技术:
- 面向对象
- canvas技术
真的写完感觉也没啥难得。还是讲讲思路吧!
实现步骤
首先的会制作粒子,粒子的制作和使用 canvas 写炫彩小球的例子差不多。不会的可以参考上篇文章 Canvas 使用指南和几个套路 里面就有这个粒子,有代码注释的很清楚。
粒子连线的原理。求直线之间的距离,使用的是数学中求直角三角形斜边的方法。
x² + y² = z²
,看数学还是很重要的。接下来只需要给定一个特定的值,来比较求得值与特定值的大小,然后根据判断结果,进行连线操作。鼠标连线和跟随。这点没人教还是挺难的,想了一个上午,下午才想出来。
- 鼠标和粒子之间的连线和粒子之间的连线原理一样的公式。不难。难得是鼠标的跟随。结合图讲。
- 假如下图中心点是粒子的话,所有在一轨道之内的粒子均可以和中心点的粒子连线。
- 假如下图中心点是鼠标的话所有三轨道之内的粒子可以和鼠标点连线。粒子之间的连线仍然以粒子为中心方圆 6000 的平方根之内。但是粒子的会在二轨道和三轨道之间向中心靠拢。假如粒子经过三轨道受向心力,向中心靠拢,到达二轨道,此时粒子运动的初始方向,与现在外加运动趋势相同,那么粒子在图中将会保持运动方向不变,穿过垂直中心线到达另一边,在另一边二轨道之内不会受到向心力的作用(物理大神现场教学)只保留自己最初的运动方向,当到达二轨道会有个向心运动趋势。粒子就会被一直固定在另一侧的二轨道附近。相反如果粒子一开始就在二轨道受向心运动且与初始位置相反,因为向心运动趋势大,粒子逃离不了,会被固定在二轨道附近。
(以上废话看不懂没关系,请看源代码注释!自己结合着理解。)
源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas实现背景动态粒子连线</title>
<style>
html,body{
margin:0;
padding:0;
width: 100%;
height:100%;
/*去掉浏览器默认垂直和水平滑动条*/
overflow:hidden;
}
</style>
</head>
<body>
<canvas></canvas>
</body>
</html>
<script>
//得到标签
var myCanvas = document.querySelector("canvas");
//设置画布的宽高为浏览器的宽高
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
//得到canvas的上下文
var ctx = myCanvas.getContext("2d");
//自适应浏览器的宽高
window.onresize = function(){
//设置画布的宽高为浏览器的宽高
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
}
// particle粒子构造函数
function Particle(){
// 随机生成粒子距离原点的x,y距离用dotx和doty来表示
this.dotx = Math.random() * myCanvas.width;
this.doty = Math.random() * myCanvas.height;
// 随机生成x,和y方向的运动信号量
do{
this.idx = (Math.random() * 2) - 1;
this.idy = (Math.random() * 2) - 1;
// 当生成的信号量为零重新生成
}while(this.idx == 0 && this.idy == 0);
// 两点之间最大距离的平方
this.max = 6000;
// 渲染粒子
this.render();
// 粒子放进数组
dotsArr.push(this);
}
// 初始化粒子
Particle.prototype.render = function(){
ctx.beginPath();
ctx.fillRect(this.dotx,this.doty,1,1);
}
// 定时器更新粒子的状态
Particle.prototype.update = function(){
// 改变每个粒子的x,y值,让粒子运动起来
this.dotx += this.idx;
this.doty += this.idy;
// 碰撞检测,防止粒子运动出浏览器
if(this.dotx > myCanvas.width || this.dotx < 0){
this.idx = -this.idx;
}
if(this.doty > myCanvas.height || this.doty < 0){
this.idy = - this.idy;
}
// 渲染粒子
this.render();
// 鼠标的中心值,当没在窗口移动鼠标,或鼠标移出窗口,鼠标的mouse.mouse_x
// 为null不进行渲染
if(mouse.mouse_x != null){
// 鼠标与各个粒子之间的x和y的距离
var mousex = this.dotx - mouse.mouse_x;
var mousey = this.doty - mouse.mouse_y;
//运用直角三角形公式 x² + y² = z²求出两点距离的平方
var mousez = mousex * mousex + mousey * mousey;
// 当粒子距离鼠标在10000~20000之间,向鼠标靠拢
if(mousez > mouse.max / 2 && mousez < mouse.max){
this.dotx -= mousex*0.03;
this.doty -= mousey*0.03;
}
// 距离鼠标平方两万以内的全部和鼠标连线
if(mousez < mouse.max){
// 调用连线功能
this.toline(mouse.mouse_x,mouse.mouse_y,mousez);
}
}
// 某一粒子实例与所有粒子距离的判断
for(let j = 0;j < dotsArr.length;j++){
// 不等于本身
if(dotsArr[j] != this){
// 实例与各个粒子之间的x和y的距离
var dx = this.dotx - dotsArr[j].dotx;
var dy = this.doty - dotsArr[j].doty;
//运用直角三角形公式 x² + y² = z²求出两点距离的平方
var dz = dx * dx + dy * dy;
// 距离鼠标平方六千以内的全部和鼠标连线
if(this.max > dz){
// 调用连线函数
this.toline(dotsArr[j].dotx,dotsArr[j].doty,dz);
}
}
}
}
// 连线函数
Particle.prototype.toline = function(x,y,z){
// 传来的鼠标与粒子距离平方大于粒子之间的距离的平方
// 确保能够得到各自的rate
if(z > this.max){
var rate = (mouse.max - z) / mouse.max;
}else{
var rate = (this.max - z) / this.max;
}
// 开始划线
ctx.beginPath();
// 线宽
ctx.lineWidth = rate / 2;
// 线的颜色
ctx.strokeStyle = "rgba(0,0,0," + (rate + 0.2) + ")";
// 线的起点
ctx.moveTo(this.dotx,this.doty);
// 线的终点
ctx.lineTo(x,y);
// 划线
ctx.stroke();
}
// 定义一个数组存放所有的粒子
var dotsArr = [];
// 向浏览器里面放入两百五十个粒子
for(let i = 0;i < 250;i++){
// 调用实例
new Particle();
}
// 定时器让粒子动起来
setInterval(function(){
// 画布清屏
ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
// 更新每个粒子
for(let i = 0;i < dotsArr.length;i++){
dotsArr[i].update();
}
},10);
// 鼠标的位置参数
var mouse = {"mouse_x":null,"mouse_y":null,"max":20000}
// 监测鼠标的移动
document.onmousemove = function(event){
mouse.mouse_x = event.clientX;
mouse.mouse_y = event.clientY;
}
document.onmouseout = function(event){
mouse.mouse_x = null;
mouse.mouse_y = null;
}
</script>
上面是使用定时器做的,在没了解 requestAnimationFrame 之前看着感觉挺不错的。很完美,但是如果使用 requestAnimationFrame 来替换定时器,动画会变得更加流畅,尤其是两者对比。下图右边使用的是定时器做的。
window.requestAnimationFrame - Web API 接口参考 | MDN
window.requestAnimationFrame() 是告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行
注意:若你想在浏览器下次重绘之前继续更新下一帧动画,那么回调函数自身必须再次调用 window.requestAnimationFrame()
看例子:
var timer = requestAnimationFrame(function(){
console.log("我被打印了!");
});
console.log(timer);
首先看出函数是异步的,其次函数默认返回一个值1
,且函数只执行了一次。所以如果想达到和定时器一样的功能必须在改进一下。改进如下:
callback();
function callback(){
var timer = requestAnimationFrame(callback);
console.log("我被打印了!",timer);
}
返回值是一个整数,请求 ID ,是回调列表中唯一的标识。是个非零值,没别的意义。你可以传这个值给 window.cancelAnimationFrame(timer)
取消一个先前通过调用window.requestAnimationFrame()方法添加到计划中的动画帧请求,以取消回调函数。
那么这个 API 的优点是什么那?window.requestAnimationFrame() 的优点就是使用系统时间来统一操作回调函数里面的数据。系统时间的频率为 60 赫兹,此API默认调用时间为 1000ms/60hz ,正是因为他统一操作这个优点,才会使动画看起来更加流畅。
改进的动态粒子连线源代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas实现背景动态粒子连线</title>
<style>
html,body{
margin:0;
padding:0;
width: 100%;
height:100%;
/*去掉浏览器默认垂直和水平滑动条*/
overflow:hidden;
}
</style>
</head>
<body>
<canvas></canvas>
</body>
</html>
<script>
//得到标签
var myCanvas = document.querySelector("canvas");
//设置画布的宽高为浏览器的宽高
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
//得到canvas的上下文
var ctx = myCanvas.getContext("2d");
//自适应浏览器的宽高
window.onresize = function(){
//设置画布的宽高为浏览器的宽高
myCanvas.width = document.documentElement.clientWidth;
myCanvas.height = document.documentElement.clientHeight;
}
// particle粒子构造函数
function Particle(){
// 随机生成粒子距离原点的x,y距离用dotx和doty来表示
this.dotx = Math.random() * myCanvas.width;
this.doty = Math.random() * myCanvas.height;
// 随机生成x,和y方向的运动信号量
do{
this.idx = (Math.random() * 2) - 1;
this.idy = (Math.random() * 2) - 1;
// 当生成的信号量为零重新生成
}while(this.idx == 0 && this.idy == 0);
// 两点之间最大距离的平方
this.max = 6000;
// 渲染粒子
this.render();
// 粒子放进数组
dotsArr.push(this);
}
// 初始化粒子
Particle.prototype.render = function(){
ctx.beginPath();
ctx.fillRect(this.dotx,this.doty,1,1);
}
// 定时器更新粒子的状态
Particle.prototype.update = function(){
// 改变每个粒子的x,y值,让粒子运动起来
this.dotx += this.idx;
this.doty += this.idy;
// 碰撞检测,防止粒子运动出浏览器
if(this.dotx > myCanvas.width || this.dotx < 0){
this.idx = -this.idx;
}
if(this.doty > myCanvas.height || this.doty < 0){
this.idy = - this.idy;
}
// 渲染粒子
this.render();
// 鼠标的中心值,当没在窗口移动鼠标,或鼠标移出窗口,鼠标的mouse.mouse_x
// 为null不进行渲染
if(mouse.mouse_x != null){
// 鼠标与各个粒子之间的x和y的距离
var mousex = this.dotx - mouse.mouse_x;
var mousey = this.doty - mouse.mouse_y;
//运用直角三角形公式 x² + y² = z²求出两点距离的平方
var mousez = mousex * mousex + mousey * mousey;
// 当粒子距离鼠标在10000~20000之间,向鼠标靠拢
if(mousez > mouse.max / 2 && mousez < mouse.max){
this.dotx -= mousex*0.03;
this.doty -= mousey*0.03;
}
// 距离鼠标平方两万以内的全部和鼠标连线
if(mousez < mouse.max){
// 调用连线功能
this.toline(mouse.mouse_x,mouse.mouse_y,mousez);
}
}
// 某一粒子实例与所有粒子距离的判断
for(let j = 0;j < dotsArr.length;j++){
// 不等于本身
if(dotsArr[j] != this){
// 实例与各个粒子之间的x和y的距离
var dx = this.dotx - dotsArr[j].dotx;
var dy = this.doty - dotsArr[j].doty;
//运用直角三角形公式 x² + y² = z²求出两点距离的平方
var dz = dx * dx + dy * dy;
// 距离鼠标平方六千以内的全部和鼠标连线
if(this.max > dz){
// 调用连线函数
this.toline(dotsArr[j].dotx,dotsArr[j].doty,dz);
}
}
}
}
// 连线函数
Particle.prototype.toline = function(x,y,z){
// 传来的鼠标与粒子距离平方大于粒子之间的距离的平方
// 确保能够得到各自的rate
if(z > this.max){
var rate = (mouse.max - z) / mouse.max;
}else{
var rate = (this.max - z) / this.max;
}
// 开始划线
ctx.beginPath();
// 线宽
ctx.lineWidth = rate / 2;
// 线的颜色
ctx.strokeStyle = "rgba(0,0,0," + (rate + 0.2) + ")";
// 线的起点
ctx.moveTo(this.dotx,this.doty);
// 线的终点
ctx.lineTo(x,y);
// 划线
ctx.stroke();
}
// 定义一个数组存放所有的粒子
var dotsArr = [];
// 向浏览器里面放入两百五十个粒子
for(let i = 0;i < 250;i++){
// 调用实例
new Particle();
}
var mouse = {"mouse_x":null,"mouse_y":null,"max":20000}
// 监测鼠标的移动
document.onmousemove = function(event){
mouse.mouse_x = event.clientX;
mouse.mouse_y = event.clientY;
}
document.onmouseout = function(event){
mouse.mouse_x = null;
mouse.mouse_y = null;
}
// 定时器让粒子动起来
callback();
function callback(){
// 画布清屏
ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
// 更新每个粒子
for(let i = 0;i < dotsArr.length;i++){
dotsArr[i].update();
}
requestAnimationFrame(callback);
}
// setInterval(function(){
// // 画布清屏
// ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
// // 更新每个粒子
// for(let i = 0;i < dotsArr.length;i++){
// dotsArr[i].update();
// }
// },10);
// 鼠标的位置参数
</script>
好了,接下来出大招,看看 canvas-nest.js 的使用。CDN 链接,最好收藏下这个网址,里面挺多库的。
<script src="https://cdn.bootcss.com/canvas-nest.js/2.0.4/canvas-nest.js"></script>
最后放下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas-nest.js</title>
</head>
<body>
</body>
</html>
<script color="99,205,205" opacity='0.9' zIndex="-2" count="199">
/**
* Copyright (c) 2016 hustcc
* License: MIT
* Version: v1.0.1
* GitHub: https://github.com/hustcc/canvas-nest.js
**/
!function(){function n(n,e,t){return n.getAttribute(e)||t}function e(n){return document.getElementsByTagName(n)}function t(){var t=e("script"),o=t.length,i=t[o-1];return{l:o,z:n(i,"zIndex",-1),o:n(i,"opacity",.5),c:n(i,"color","0,0,0"),n:n(i,"count",99)}}function o(){a=m.width=window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,c=m.height=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight}function i(){r.clearRect(0,0,a,c);var n,e,t,o,m,l;s.forEach(function(i,x){for(i.x+=i.xa,i.y+=i.ya,i.xa*=i.x>a||i.x<0?-1:1,i.ya*=i.y>c||i.y<0?-1:1,r.fillRect(i.x-.5,i.y-.5,1,1),e=x+1;e<u.length;e++)n=u[e],null!==n.x&&null!==n.y&&(o=i.x-n.x,m=i.y-n.y,l=o*o+m*m,l<n.max&&(n===y&&l>=n.max/2&&(i.x-=.03*o,i.y-=.03*m),t=(n.max-l)/n.max,r.beginPath(),r.lineWidth=t/2,r.strokeStyle="rgba("+d.c+","+(t+.2)+")",r.moveTo(i.x,i.y),r.lineTo(n.x,n.y),r.stroke()))}),x(i)}var a,c,u,m=document.createElement("canvas"),d=t(),l="c_n"+d.l,r=m.getContext("2d"),x=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(n){window.setTimeout(n,1e3/45)},w=Math.random,y={x:null,y:null,max:2e4};m.id=l,m.style.cssText="position:fixed;top:0;left:0;z-index:"+d.z+";opacity:"+d.o,e("body")[0].appendChild(m),o(),window.onresize=o,window.onmousemove=function(n){n=n||window.event,y.x=n.clientX,y.y=n.clientY},window.onmouseout=function(){y.x=null,y.y=null};for(var s=[],f=0;d.n>f;f++){var h=w()*a,g=w()*c,v=2*w()-1,p=2*w()-1;s.push({x:h,y:g,xa:v,ya:p,max:6e3})}u=s.concat([y]),setTimeout(function(){i()},100)}();
</script>
插件的作用和我们写的功能一模一样。