星空连线背景

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas星空连线背景</title>
<style>
* {
margin: 0; 
padding: 0;
}
#canvas{
background: #000;
display: block;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
//命名空间
var Canvas = {};
Canvas.animate = {
//初始化
init: function(){
var canvas = document.getElementById('canvas');
this.cxt = canvas.getContext("2d");//2d绘图环境 画笔
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
this.cw = canvas.width;
this.ch = canvas.height;
this.num = 200;
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){
var cxt = this.cxt;
cxt.save();
cxt.fillStyle = "pink";
cxt.beginPath();
cxt.arc(x,y,0.5,0,Math.PI*2,false);
cxt.closePath();
cxt.fill();
cxt.restore();
},
//绘制线条
drawLine: function(x1,y1,x2,y2){
var cxt = this.cxt;
var color = cxt.createLinearGradient(x1,y1,x2,y2);
color.addColorStop(0,"#fff");
color.addColorStop(0.5,"green");
color.addColorStop(1,"#333");
cxt.save();
cxt.strokeStyle = color;
cxt.beginPath();
cxt.moveTo(x1,y1);
cxt.lineTo(x2,y2);
cxt.closePath();
cxt.stroke();
cxt.restore();
},
//鼠标连线
drawMouseLine: function(){

},
//粉色小点动起来 及连线
moveCircle: function(){
this.cxt.clearRect(0,0,this.cw,this.ch);
for(var i = 0;i<this.num;i++){
this.data[i].x+=this.data[i].cX;
this.data[i].y+=this.data[i].cY;
//边界值判断
if(this.data[i].x>this.cw||this.data[i].x<0){
this.data[i].cX = -this.data[i].cX;
}
if(this.data[i].y>this.ch||this.data[i].y<0){
this.data[i].cY = -this.data[i].cY;
}
this.drawCircle(this.data[i].x,this.data[i].y);
//用勾股定理判断是否连线
for(var j = i+1;j<this.num;j++){//下一个点 i++
if((this.data[i].x-this.data[j].x)*(this.data[i].x-this.data[j].x)+
(this.data[i].y-this.data[j].y)*(this.data[i].y-this.data[j].y)<=50*50){
this.drawLine(this.data[i].x,this.data[i].y,this.data[j].x,this.data[j].y);
}
}
}
}
}
Canvas.animate.init();
setInterval(function(){
Canvas.animate.moveCircle();
},13);
</script>
</body>
</html>
WEB前端学习交流群21 598399936
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值