原创 15320107723 随笔超实用的代码段 1.2k 阅读 2017-10-29 23:04:31 举报
- <!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>
canvas
JavaScript
HTML5
评论
2
喜欢
12
赞
7
评论 ( 2 )
走你
最新评论
来源: http://www.qdfuns.com/article/35646/44cb2fd26a3913bab42eef793abc9b0f.html