<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>canvas场景连线特效</title>
<style type="text/css">
body{
margin:0;
padding:0;
}
#canvas{
display:block;
background:#000;
}
</style>
</head>
<body>
<canvas id="canvas">
</canvas>
<script type="text/javascript">
/*var canvas=document.getElementById("canvas");
var cxt=canvas.getContext("2d");//画笔*/
var Canvas={
//初始化:是所有人都要遵循的
//this在当前Canvas的作用域下相当于一个全局变量
init:function(){
var canvas=document.getElementById("canvas");
this.cxt=canvas.getContext("2d");//画笔
//浏览器和网页等高等宽
canvas.width=window.innerWidth;
canvas.height=window.innerHeight;
this.cw=canvas.width;
this.ch=canvas.height;
this.num=300;//创建小圆点的个数
this.data=[];//存储小圆点的数据
for(var i=0;i<this.num;i++){
this.data[i]={
x:Math.random()*this.cw,
y:Math.random()*this.ch,
cX:Math.random()*0.6-0.3,
cY:Math.random()*0.6-0.3
}
this.drawCircle(this.data[i].x,this.data[i].y);
}
},
//绘制粉色小点
drawCircle:function(x,y){
cxt=this.cxt;
cxt.save();//保存路径
cxt.fillStyle='pink';//圆的填充颜色粉红色
cxt.beginPath();//开始路径
cxt.arc(x,y,1,0,Math.PI*2,false);//绘画方法
cxt.closePath();//结束路径
cxt.fill();//填充
cxt.restore();//释放路径
},
//小圆点运动
moveCricle:function(){
var self=this;
var cw=this.cw;
var ch=this.ch;
self.cxt.clearRect(0,0,cw,ch);//先让整个画布清空
//然后在绘画下一个点
for(var i=0;i<self.num;i++){
self.data[i].x+=self.data[i].cX;
self.data[i].y+=self.data[i].cY;
//碰撞的边界值检测
if(self.data[i].x>cw||self.data[i].x<0){
self.data[i].cX=-self.data[i].cX;
}
if(self.data[i].y>ch||self.data[i].y<0){
self.data[i].cY=-self.data[i].cY;
}
self.drawCircle(self.data[i].x,self.data[i].y);
//用勾股定理判断是否连线
for(var j=i+1;j<self.num;j++){//下一点的循环
if(Math.pow(self.data[i].x-self.data[j].x,2)+Math.pow(self.data[i].y-self.data[j].y,2)<=50*50){
self.drawLine(self.data[i].x,self.data[i].y,self.data[j].x,self.data[j].y,false);
}
}
if(move.x){
if(Math.pow(self.data[i].x-move.x,2)+Math.pow(self.data[i].y-move.y,2)<=50*50){
self.drawLine(self.data[i].x,self.data[i].y,move.x,move.y,true);
}
}
}
},
//绘制线条
drawLine:function(x1,y1,x2,y2,isMove){
var cxt=this.cxt;
var color=cxt.createLinearGradient(x1,y1,x2,y2);
if(!isMove){
color.addColorStop(0.5,"yellow");
color.addColorStop(1,"red");
}
else{
color.addColorStop(0.5,"#ccc");
color.addColorStop(1,"#06c");
}
cxt.strokeStyle=color;
cxt.beginPath();
cxt.moveTo(x1,y1);
cxt.lineTo(x2,y2);
cxt.closePath();
cxt.stroke();//填充方式,画线
cxt.restore();
}
}
var move={};
document.addEventListener("mousemove",function(e){
move.x=e.clientX;
move.y=e.clientY;
},false)
Canvas.init();
//时间控件
setInterval(function(){
Canvas.moveCricle();
},0.5)
</script>
</body>
</html>
效果:
代码实例下载:链接:https://pan.baidu.com/s/1A3-AzBiCfrqZy4oHELI3-w
提取码:9bb6
复制这段内容后打开百度网盘手机App,操作更方便哦